JTree常用操作

一。遍历节点

 

   private void visitAllNodes(TreeNode node,List lst){
      if(node.getChildCount()>0){
            for (Enumeration e = node.children(); e.hasMoreElements();) {
                MyTreeNode n = (MyTreeNode) e.nextElement();
                if (n.getUserObject() instanceof FormStyle) {
                    lst.add(((FormStyle)n.getUserObject()));
                }
                visitAllNodes(n,lst);
            } 
        }
    }

 
二。节点上添加复选框

 

 

public class TreeIconCellRenderer extends JPanel implements TreeCellRenderer {

    private JCheckBox check = new JCheckBox();
    private CheckBoxTreeLabel label = new CheckBoxTreeLabel();
    private final ImageIcon CATALOG_IMG = new ImageIcon(getClass().getResource("/client/system/formtype/resource/folder.gif"));
    private final ImageIcon CATALOG_OPEN_IMG = new ImageIcon(getClass().getResource("/client/system/formtype/resource/folder-expanded.gif"));
    private final ImageIcon CLASS_IMG = new ImageIcon(getClass().getResource("/client/system/formtype/resource/parenticon.gif"));
    private JLabel lblIcon = new JLabel();

    public TreeIconCellRenderer() {

        check.setBackground(UIManager.getColor("Tree.textBackground"));
        label.setForeground(UIManager.getColor("Tree.textForeground"));
        setFont(new Font("宋体", 0, 12));
        setLayout(new FlowLayout(0, 0, 1));//这几个设置要注意,不然jtree显示样式看起来很别扭
        this.label.setFont(new Font("宋体", 0, 12));
        this.label.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
        this.check.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 0));
        this.check.setMargin(new Insets(0, 0, 0, 0));
        add(lblIcon);
        add(check);
        add(label);
        setOpaque(false);
        label.setBackground(UIManager.getColor("Tree.selectionBackground"));
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean sel,
            boolean expanded,
            boolean leaf, int row,
            boolean hasFocus) {
        // super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
        String stringValue = tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus);
        setEnabled(tree.isEnabled());
        check.setSelected(((MyTreeNode) value).isSelected());

        label.setFont(tree.getFont());
        label.setText(stringValue);
        label.setSelected(sel);
        label.setFocus(hasFocus);
        if (sel) {
            this.label.setOpaque(true);
        } else {
            this.label.setOpaque(false);
        }
        MyTreeNode node = (MyTreeNode) value;
        Object obj = node.getUserObject();

        lblIcon.setIcon(CATALOG_IMG);
        if (expanded) {
            lblIcon.setIcon(CATALOG_OPEN_IMG);
        }
        if (obj instanceof FormClass) {
            lblIcon.setIcon(CLASS_IMG);
        }
        if (obj instanceof FormStyle) {
            lblIcon.setIcon(CLASS_IMG);
        }

        label.setText(node.toString());
        return this;
    }
}

class CheckBoxTreeNodeSelectionListener extends MouseAdapter {

    public void mouseClicked(MouseEvent event) {
        JTree tree = (JTree) event.getSource();
        int x = event.getX();
        int y = event.getY();
        int row = tree.getRowForLocation(x, y);
        TreePath path = tree.getPathForRow(row);
        if (path != null) {
            MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
            if (node != null) {
                boolean isSelected = !node.isSelected();
                node.setSelected(isSelected);
                ((DefaultTreeModel) tree.getModel()).nodeStructureChanged(node);
            }
        }
    }
}

 public class MyTreeNode extends DefaultMutableTreeNode {

    private boolean isSelected;

    public MyTreeNode(Object userObject) {
        super(userObject);
    }

    public boolean isSelected() {
        return isSelected;
    }

    public String toString() {
        if (userObject != null) {
            if (userObject instanceof FormCataLog) {
                FormCataLog catalog = (FormCataLog) userObject;
                return catalog.getName();
            } else if (userObject instanceof FormClass) {
                FormClass classForm = (FormClass) userObject;
                return classForm.getName();
            } else if (userObject instanceof FormClassItem) {
                FormClassItem itemForm = (FormClassItem) userObject;
                return itemForm.getItemlabel();
            } else if (userObject instanceof FormStyle) {
                FormStyle formStyle = (FormStyle) userObject;
                return formStyle.getName();
            } else {
                return super.toString();
            }
        }
        return super.toString();

    }

    public void setSelected(boolean _isSelected) {
        this.isSelected = _isSelected;

        if (_isSelected) {
            // 如果选中,则将其所有的子结点都选中  
            if (children != null) {
                for (Object obj : children) {
                    MyTreeNode node = (MyTreeNode) obj;
                    if (_isSelected != node.isSelected()) {
                        node.setSelected(_isSelected);
                    }
                }
            }
            // 向上检查,如果父结点的所有子结点都被选中,那么将父结点也选中  
            MyTreeNode pNode = (MyTreeNode) parent;
            // 开始检查pNode的所有子节点是否都被选中  
            if (pNode != null) {
                int index = 0;
                for (; index < pNode.children.size(); ++index) {
                    MyTreeNode pChildNode = (MyTreeNode) pNode.children.get(index);
                    if (!pChildNode.isSelected()) {
                        break;
                    }
                }
                /*   
                 * 表明pNode所有子结点都已经选中,则选中父结点,  
                 * 该方法是一个递归方法,因此在此不需要进行迭代,因为  
                 * 当选中父结点后,父结点本身会向上检查的。  
                 */
                if (index == pNode.children.size()) {
                    if (pNode.isSelected() != _isSelected) {
                        pNode.setSelected(_isSelected);
                    }
                }
            }
        } else {
            /*  
             * 如果是取消父结点导致子结点取消,那么此时所有的子结点都应该是选择上的;  
             * 否则就是子结点取消导致父结点取消,然后父结点取消导致需要取消子结点,但  
             * 是这时候是不需要取消子结点的。  
             */
            if (children != null) {
                int index = 0;
                for (; index < children.size(); ++index) {
                    MyTreeNode childNode = (MyTreeNode) children.get(index);
                    if (!childNode.isSelected()) {
                        break;
                    }
                }
                // 从上向下取消的时候  
                if (index == children.size()) {
                    for (int i = 0; i < children.size(); ++i) {
                        MyTreeNode node = (MyTreeNode) children.get(i);
                        if (node.isSelected() != _isSelected) {
                            node.setSelected(_isSelected);
                        }
                    }
                }
            }

            // 向上取消,只要存在一个子节点不是选上的,那么父节点就不应该被选上。  
            MyTreeNode pNode = (MyTreeNode) parent;
            if (pNode != null && pNode.isSelected() != _isSelected) {
                pNode.setSelected(_isSelected);
            }
        }
    }
}

 public class CheckBoxTreeLabel extends JLabel {

    private boolean isSelected;
    private boolean hasFocus;

    public CheckBoxTreeLabel() {
    }

    public void setBackground(Color color) {
        if (color instanceof ColorUIResource) {
            color = null;
        }
        super.setBackground(color);
    }

    public void paint(Graphics g) {
        String str;
        if ((str = getText()) != null) {
            if (0 < str.length()) {
                if (isSelected) {
                    g.setColor(UIManager.getColor("Tree.selectionBackground"));
                } else {
                    g.setColor(UIManager.getColor("Tree.textBackground"));
                }
                Dimension d = getPreferredSize();
                int imageOffset = 0;
                Icon currentIcon = getIcon();
                if (currentIcon != null) {
                    imageOffset = currentIcon.getIconWidth() + Math.max(0, getIconTextGap() - 1);
                }
                g.fillRect(imageOffset, 0, d.width - 1 - imageOffset, d.height);
                if (hasFocus) {
                    g.setColor(UIManager.getColor("Tree.selectionBorderColor"));
                    g.drawRect(imageOffset, 0, d.width - 1 - imageOffset, d.height - 1);
                }
            }
        }
        super.paint(g);
    }

    public Dimension getPreferredSize() {
        Dimension retDimension = super.getPreferredSize();
        if (retDimension != null) {
            retDimension = new Dimension(retDimension.width + 3, retDimension.height);
        }
        return retDimension;
    }

    public void setSelected(boolean isSelected) {
        this.isSelected = isSelected;
    }

    public void setFocus(boolean hasFocus) {
        this.hasFocus = hasFocus;
    }
}

 
三。节点上下移动

 

private void nodeUpMove() {
        
        TreePath path = jTree1.getSelectionPath();
        Pnode = path.getLastPathComponent();
        if (Pnode == null || Pnode == root) {
            return;
        }
        MenuTreeModel DTreeModel = (MenuTreeModel) jTree1.getModel();
        int index = DTreeModel.getIndexOfChild(((DefaultMutableTreeNode) Pnode).getParent(), cNode);
        if (index > 0) {
            DTreeModel.insertNodeInto((DefaultMutableTreeNode) Pnode, (DefaultMutableTreeNode) ((DefaultMutableTreeNode) Pnode).getParent(), index - 1);
        }
        DTreeModel.reload();
        TreePath visiblePath = new TreePath( ( (DefaultTreeModel) jTree1.getModel()).getPathToRoot((DefaultMutableTreeNode)Pnode));
        jTree1.setSelectionPath(visiblePath);
    }

  private void nodeDownMove() {      

        TreePath path = jTree1.getSelectionPath();
        Pnode = path.getLastPathComponent();
         if (Pnode == null || Pnode == root) {
            return;
        }
        MenuTreeModel DTreeModel = (MenuTreeModel) jTree1.getModel();
        int index = DTreeModel.getIndexOfChild(((DefaultMutableTreeNode) Pnode).getParent(), Pnode);
        if (index < ((DefaultMutableTreeNode)Pnode).getParent().getChildCount()-1) {
            DTreeModel.insertNodeInto((DefaultMutableTreeNode) Pnode, (DefaultMutableTreeNode) ((DefaultMutableTreeNode) Pnode).getParent(), index+1);
        }
        DTreeModel.reload();
        TreePath visiblePath = new TreePath( ( (DefaultTreeModel) jTree1.getModel()).getPathToRoot((DefaultMutableTreeNode)Pnode));
        jTree1.setSelectionPath(visiblePath);
    }
 

四。

五。

六。

七。

 

你可能感兴趣的:(JTree)