How to change style (color, font) of a single JTree node

后端 未结 2 375
谎友^
谎友^ 2020-12-21 01:43

I have two JTree in two panels in a JFrame. I want to change the style(color and font) of nodes on drag and drop from one tree to the other.Please

2条回答
  •  一整个雨季
    2020-12-21 02:17

    Create your own CellRenderer. To give the appropriate behaviour to your MyTreeCellRenderer, you will have to extend DefaultTreecellRenderer and override the getTreeCellRendererComponent method.

    public class MyTreeCellRenderer extends DefaultTreeCellRenderer {
    
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);
    
            // Assuming you have a tree of Strings
            String node = (String) ((DefaultMutableTreeNode) value).getUserObject();
    
            // If the node is a leaf and ends with "xxx"
            if (leaf && node.endsWith("xxx")) {
                // Paint the node in blue
                setForeground(new Color(13, 57 ,115));
            }
    
            return this;
        }
    }
    

    Finally, say your tree is called myTree, set your CellRenderer to it:

    myTree.setCellRenderer(new MyTreeCellRenderer());
    

提交回复
热议问题