`
收藏列表
标题 标签 来源
24 24
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BasicDataLookupDialog.java
 *
 * Created on 2010-3-4, 13:42:39
 */
package com.itown.rcp.basicdata.view;

import com.itown.rcp.basicdata.BasicData;
import com.itown.rcp.basicdata.BasicDataDefine;

import com.itown.rcp.basicdata.BasicDataException;
import com.itown.rcp.basicdata.TreeBasicDataDefine;
import com.itown.rcp.basicdata.impl.BasicDataFactory;
import com.itown.rcp.basicdata.impl.BasicDataUtils;
import com.itown.rcp.client.ShortcutManager;
import com.itown.rcp.client.test.AuthenticatedTestBase;
import com.itown.rcp.swing.fsp.filter.FilterItem;
import com.itown.rcp.swing.lookup.Lookupable;
import com.itown.rcp.swing.table.TableConfig;
import com.itown.rcp.swing.tree.CheckNode;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author yingwl
 */
public class BasicDataLookupDialog extends javax.swing.JDialog implements Lookupable {

    private BasicDataLookupContentPane lookupContent;
    private Object selectedValue;
    private boolean onlySelectLeafNode = false;
    /**
     * 解析参数,格式如: SysCompany{code:companyCode,name:companyName}
     * 解析后存放到entityName及propsMap
     */
    private String entityName;
    private Map propsMap = new HashMap();
    private boolean isInit;
    private boolean multiSelected = false;
    private boolean dgInSelection = false;
    private BasicDataDefine basicDataDefine;
    //树形基础数据的根节点
    private String[] rootCodes;
    private TableConfig tableConfig;

    public String[] getRootCodes() {
        return rootCodes;
    }

    public void setRootCodes(String[] rootCodes) {

        this.rootCodes = rootCodes;
        if (rootCodes != null) {
            this.isInit = false;
        }
    }

    public TableConfig getTableConfig() {
        return tableConfig;
    }

    public void setTableConfig(TableConfig tableConfig) {
        this.tableConfig = tableConfig;
        if (tableConfig != null) {
            this.isInit = false;
        }
    }
    /**
     * 显示查询对话框时的名称与代码的查询值
     */
    private QueryCondition condition;
    ShortcutManager.ShortcutListener f6action = new ShortcutManager.ShortcutListener() {

        public void handle() {
            codeTextField.requestFocus();
        }
    };
    ShortcutManager.ShortcutListener f7action = new ShortcutManager.ShortcutListener() {

        public void handle() {
            nameTextField.requestFocus();
        }
    };
    ShortcutManager.ShortcutListener f8action = new ShortcutManager.ShortcutListener() {

        public void handle() {
            Component com = lookupContent.getComponent();
            if (com instanceof JTable) {
                JTable table = (JTable) com;
                if (table.getRowCount() > 0) {
                    //table.getSelectionModel().setSelectionInterval(0, 0);
                }
                table.requestFocus();
            }
        }
    };

    public BasicDataLookupDialog() {
        super((java.awt.Frame) null, true);

        initComponents();
        this.setTitle("基础数据查询");

//        createRootPane();

        //设置图标

    }

    @Override
    protected JRootPane createRootPane() {

        ActionListener actionListener_Esc = new ActionListener() {

            public void actionPerformed(ActionEvent actionEvent) {
                dispose();
            }
        };
        JRootPane rootPane1 = new JRootPane();
        rootPane1.registerKeyboardAction(actionListener_Esc, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);
        return rootPane1;
    }

    public BasicDataLookupDialog(boolean multiSelected) {
        this();
        this.multiSelected = multiSelected;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        contentPane = new javax.swing.JPanel();
        queryPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        codeTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        queryButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();
        buttonPanel = new javax.swing.JPanel();
        okButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        contentPane.setLayout(new java.awt.BorderLayout());

        jLabel1.setText("代码:");
        queryPanel.add(jLabel1);

        codeTextField.setName("code"); // NOI18N
        codeTextField.setPreferredSize(new java.awt.Dimension(80, 21));
        codeTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                codeTextFieldKeyReleased(evt);
            }
        });
        queryPanel.add(codeTextField);

        jLabel2.setText("名称:");
        queryPanel.add(jLabel2);

        nameTextField.setName("name"); // NOI18N
        nameTextField.setPreferredSize(new java.awt.Dimension(80, 21));
        nameTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                nameTextFieldKeyReleased(evt);
            }
        });
        queryPanel.add(nameTextField);

        queryButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/search.gif"))); // NOI18N
        queryButton.setText("查询");
        queryButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                queryButtonActionPerformed(evt);
            }
        });
        queryPanel.add(queryButton);

        resetButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/congzhi.gif"))); // NOI18N
        resetButton.setText("重置");
        resetButton.setName("resetButton"); // NOI18N
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });
        queryPanel.add(resetButton);

        okButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/ok.gif"))); // NOI18N
        okButton.setText("确定");
        okButton.setName("okButton"); // NOI18N
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(okButton);

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16_16/cencel.gif"))); // NOI18N
        cancelButton.setText("取消");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(cancelButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(queryPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
            .addComponent(buttonPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
            .addComponent(contentPane, javax.swing.GroupLayout.DEFAULT_SIZE, 427, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(queryPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(contentPane, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                        

    private void queryTable() {
        JTable queryTable = (JTable) lookupContent.getComponent();
        int rows = queryTable.getRowCount();
        if (rows == 1) {
            ok();
        }
    }
    private void codeTextFieldKeyReleased(java.awt.event.KeyEvent evt) {                                          
        if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
            doQuery();
        }
}                                         

    private void nameTextFieldKeyReleased(java.awt.event.KeyEvent evt) {                                          
        if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
            doQuery();
        }
}                                         
    private void doQuery() {
        if (basicDataDefine instanceof TreeBasicDataDefine) {//tree
            this.queryButton.doClick();
            //是否有查询结果,如果只有一条记录,则执行ok();
            JTree tree = (JTree) lookupContent.getComponent();
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
            if (root.getChildCount() == 1) {
                DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getFirstChild();
                if (child.getChildCount() == 0) {
                    tree.setSelectionPath(new TreePath(child.getPath()));
                    if (child instanceof CheckNode){
                        CheckNode cnode = (CheckNode) child;
                        cnode.setSelected(true, tree);
                    }
                    ok();
                }
            }
        } else {
            queryTable();
            this.queryButton.doClick();
        }
    }
    private void queryButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        this.lookupContent.query(codeTextField, nameTextField);
}                                           

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        codeTextField.setText("");
        nameTextField.setText("");
        lookupContent.query(codeTextField, nameTextField);
}                                           

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {                                         
        removeAction();
        ok();
}                                        

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
        okButtonClicked = false;
        removeAction();
        this.dispose();
}                                            

    private void removeAction() {
//        ShortcutManager.getInstance().removeShortcutListener(f6action);
//        ShortcutManager.getInstance().removeShortcutListener(f7action);
//        ShortcutManager.getInstance().removeShortcutListener(f8action);
    }

    public void ok() throws HeadlessException {
        if (lookupContent.getSelectedObjects() != null) {
            okButtonClicked = true;
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(this, "请选择一条记录。");
        }
    }

    public boolean isMultiSelected() {
        return multiSelected;
    }

    public void setMultiSelected(boolean multiSelected) {
        this.multiSelected = multiSelected;
    }

    public boolean isOnlySelectLeafNode() {
        return onlySelectLeafNode;
    }

    public void setOnlySelectLeafNode(boolean onlySelectLeafNode) {
        if (this.lookupContent != null && lookupContent instanceof TreeBasicDataLookupPane) {
            TreeBasicDataLookupPane treePane = (TreeBasicDataLookupPane) lookupContent;
            treePane.setOnlySelectLeafNode(onlySelectLeafNode);
        }
        this.onlySelectLeafNode = onlySelectLeafNode;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                AuthenticatedTestBase testBase = new AuthenticatedTestBase("root", "root");
                BasicDataLookupDialog dialog = new BasicDataLookupDialog();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setParams("SysCompany{code:companyCode,name:companyName}");
                Object result = dialog.getResult(null);
                System.out.println(result);


            }
        });
    }
    private String propertyName = null;

    @Override
    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    @Override
    public void setSelectedValue(JTable table, Object value) {
        this.selectedValue = value;
    }

    public BasicDataDefine getBasicDataDefine() {
        return basicDataDefine;
    }

    public void setBasicDataDefine(BasicDataDefine basicDataDefine) {
        this.basicDataDefine = basicDataDefine;
    }

    @Override
    public boolean validate(Object value) {
        return true;
    }

    private String getKey(String text) {
        return entityName + text;
    }

    private Object getEntityFromCache(String text) {
        return entityCache.get(text);
    }
    private static Map entityCache = Collections.synchronizedMap(new WeakHashMap());

    private Object findEntity(
            String text) {
        String key = getKey(text);

        Object result = getEntityFromCache(key);
        if (result != null) {

            return result;
        }
        synchronized (key) {
            BasicData basicData = BasicDataFactory.getInstance().getBasicData(entityName);
            result = basicData.getEntity(text);
            putEntityToCache(key, result);
        }

        return result;
    }

    private void putEntityToCache(String text, Object result) {
        entityCache.put(text, result);
    }

    public String getTitle(Object value) {
        Object name = "";
        if (value == null) {
            return "";
        }
        String codeValue = value.toString();

        Object entity = this.findEntity(codeValue);
        if (entity == null) {
            return codeValue;
        }

        String nameProperty = BasicDataUtils.getBasicDataDefine(entityName).getNamePropertyName();
        try {
            return codeValue + "[" + BeanUtils.getSimpleProperty(entity, nameProperty) + "]";
        } catch (Exception ex) {
            throw new BasicDataException("基础数据:" + name + "获取名称失败", ex);
        }

    }
    private String params;

    @Override
    public void setParams(String params) {
        this.params = params.trim();
        parseParams(getParams());
    }

    public String getPropertyName() {
        return propertyName;
    }

    public String getParams() {
        return params;
    }

    public String getBasicDataId() {
        return entityName;
    }
    private boolean okButtonClicked = false;

    public synchronized Object getResult(JTable table) {

        Object result = null;
        this.init();

        this.setVisible(true);
        if (okButtonClicked) {
            result = lookupContent.getSelectedObjects();
        }
        return result;
    }

    public synchronized List getReturnEntities() {

        List result = null;
        this.init();

        this.setVisible(true);
        if (okButtonClicked) {
            result = lookupContent.getSelectedEntities();
        }
        return result;
    }
    private FilterItem customizerFilter;

    public FilterItem getCustomizerFilter() {
        return customizerFilter;
    }

    public QueryCondition getCondition() {
        return condition;
    }

    public void setCondition(QueryCondition condition) {
        this.condition = condition;
        if (condition != null) {
            codeTextField.setText(condition.getCode() == null ? "" : condition.getCode());
            nameTextField.setText(condition.getName() == null ? "" : condition.getName());
        } else {
            codeTextField.setText("");
            nameTextField.setText("");
        }

        this.isInit = false;
    }

    public void setCustomizerFilter(FilterItem customizerFilter) {
        this.customizerFilter = customizerFilter;
        this.isInit = false;
    }

    public boolean isDgInSelection() {
        return dgInSelection;
    }

    public void setDgInSelection(boolean dgInSelection) {
        this.dgInSelection = dgInSelection;
    }

    public String getEntityName() {
        return entityName;
    }

    private synchronized void init() {
        if (!isInit) {

            if (lookupContent == null) {
                if (basicDataDefine instanceof TreeBasicDataDefine) {//tree

                    lookupContent = new TreeBasicDataLookupPane((TreeBasicDataDefine) basicDataDefine, propsMap, this.getCustomizerFilter(), this.multiSelected, this.condition, dgInSelection, rootCodes, this.onlySelectLeafNode);



                    JTree tree = (JTree) lookupContent.getComponent();;
                    tree.addKeyListener(new KeyListener() {

                        public void keyTyped(KeyEvent e) {
                            System.out.println("-----------1----------------------");
                        }

                        public void keyPressed(KeyEvent e) {
                            System.out.println("-----------2----------------------");
                        }

                        public void keyReleased(KeyEvent evt) {

                            if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
                                System.out.println("-----------3----------------------");
                                ok();

                            }
                        }
                    });

//                tree.getBasicDataTree().addMouseListener(new OKMouseListener());
                } else {
                    lookupContent = new ListBasicDataLookupPane(basicDataDefine, propsMap, getCustomizerFilter(), multiSelected, this.codeTextField, this.nameTextField);

                }

                contentPane.add((Component) lookupContent);

                ActionMap am = (ActionMap) UIManager.get("Table.actionMap");
                if (am != null) {
                    am.put("selectNextRowCell", new AbstractAction() {

                        public void actionPerformed(ActionEvent e) {

                            ok();
                        }
                    });
                }

                ActionMap actionMap = lookupContent.getActionMap();
                InputMap inputMap = lookupContent.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
                actionMap.put(KeyEvent.VK_F6, new AbstractAction() {

                    public void actionPerformed(ActionEvent e) {
                        codeTextField.requestFocus();
                    }
                });
                actionMap.put(KeyEvent.VK_F7, new AbstractAction() {

                    public void actionPerformed(ActionEvent e) {
                        nameTextField.requestFocus();
                    }
                });
                actionMap.put(KeyEvent.VK_F8, new AbstractAction() {

                    public void actionPerformed(ActionEvent e) {
                        Component com = lookupContent.getComponent();
                        if (com instanceof JTable) {
                            JTable table = (JTable) com;
                            if (table.getRowCount() > 0) {
                                //table.getSelectionModel().setSelectionInterval(0, 0);
                            }
                            table.requestFocus();
                        } else if (com instanceof JTree) {
                            JTree tree = (JTree) com;
                            TreeModel model = tree.getModel();
                            DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();

                            if (root.getChildCount() > 0) {

                                DefaultMutableTreeNode firstNode = (DefaultMutableTreeNode) root.getFirstChild();

                                tree.setSelectionPath(new TreePath(firstNode.getPath()));
                            }
                            tree.requestFocus();

                        }
                    }
                });

                KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0, true);
                inputMap.put(keyStroke, KeyEvent.VK_F6);

                KeyStroke keyStroke7 = KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0, true);
                inputMap.put(keyStroke7, KeyEvent.VK_F7);

                KeyStroke keyStroke8 = KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0, true);
                inputMap.put(keyStroke8, KeyEvent.VK_F8);

                lookupContent.getComponent().addMouseListener(new OKMouseListener());


                this.pack();
                isInit = true;
            }

            if (!isInit) {
                if (basicDataDefine == null) {
                    throw new BasicDataException("没有找到基础数据定义:" + entityName);
                }

                if (lookupContent instanceof TreeBasicDataLookupPane) {
                    TreeBasicDataLookupPane treePane = (TreeBasicDataLookupPane) lookupContent;
                    treePane.init((TreeBasicDataDefine) basicDataDefine, propsMap, this.getCustomizerFilter(), this.multiSelected, this.condition, dgInSelection, rootCodes);
                } else if (lookupContent instanceof ListBasicDataLookupPane) {
                    ListBasicDataLookupPane listPane = (ListBasicDataLookupPane) lookupContent;
                    listPane.init(basicDataDefine, propsMap, getCustomizerFilter(), multiSelected, this.codeTextField, this.nameTextField, tableConfig);
                }
            }
            isInit = true;
        }
        try {
            Thread.currentThread().sleep(100);
        } catch (InterruptedException ex) {
            Logger.getLogger(BasicDataLookupDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        
                lookupContent.locate(selectedValue);
           
        

        Toolkit kit = Toolkit.getDefaultToolkit();    // 定义工具包
        Dimension screenSize = kit.getScreenSize();   // 获取屏幕的尺寸
        int screenWidth = screenSize.width / 2;         // 获取屏幕的宽
        int screenHeight = screenSize.height / 2;       // 获取屏幕的高
        int height = this.getHeight();
        int width = this.getWidth();
        setLocation(screenWidth - width / 2, screenHeight - height / 2);
    }

    class OKMouseListener extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("mouse event : " + e.getClickCount());
            if (e.getClickCount() > 1) {
                ok();
            }
        }
    }

    private void parseParams(String params) {
        int location = params.indexOf("{");
        entityName = params.substring(0, location);
        String others = params.substring(location);
        others = others.substring(1, others.lastIndexOf("}"));
        String[] arrays = others.split(",");
        basicDataDefine = BasicDataUtils.getBasicDataDefine(entityName);
        for (int i = 0; i < arrays.length; i++) {
            propsMap.put(arrays[i].substring(0, arrays[i].indexOf(":")).trim(), arrays[i].substring(arrays[i].indexOf(":") + 1).trim());
        }
    }

    public Map getPropsMap() {
        return propsMap;
    }

    public static class QueryCondition {

        private String code;
        private String name;

        public QueryCondition() {
        }

        public QueryCondition(String code, String name) {
            this.code = code;
            this.name = name;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JTextField codeTextField;
    private javax.swing.JPanel contentPane;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton okButton;
    private javax.swing.JButton queryButton;
    private javax.swing.JPanel queryPanel;
    private javax.swing.JButton resetButton;
    // End of variables declaration                   
}
Global site tag (gtag.js) - Google Analytics