Change The icon of a certain Node in JTree?

2019-08-08 19:38发布

问题:

I have a JTree and nodes of it are driven from DefaultMutableTreeNode. Each node can be verify or not.At first the icon of all nodes are the same but, I am going to change the ICON of the verified nodes when I select them and press the verify button.I want to have the ability to click and write on each node so I can not use JLabel to show icons. I made the following code but it returns NULLException.

class CustomIconRenderer extends DefaultTreeCellRenderer {
        ImageIcon defaultIcon;
        ImageIcon specialIcon;
        ImageIcon closeIcon;
        static DefaultTreeModel model;
        static myDefaultMutableTreeNode root;

        public CustomIconRenderer() 
        {
            openIcon = new ImageIcon(CustomIconRenderer.class.getResource("icons/question.png"));
            closeIcon = new ImageIcon(CustomIconRenderer.class.getResource("icons/Target-New-Logo.jpg"));
            setLeafIcon(closeIcon);
        }

        @Override
        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);
               Object nodeObj = ((DefaultMutableTreeNode)value).getUserObject();

          Check_each_nodes_are_verified_change_the_icon();
          return this;
        }
    }

    public class myDefaultMutableTreeNode extends DefaultMutableTreeNode{

        private static int id=0;
        private int nodeid;
        private int verify;
        private int depth;

    }

Millions Thanks.

回答1:

The DefaultTreeCellRenderer has setters, allowing to set open icon, closed icon and leaf icon. Inside the overridden getTreeCellRendererComponent, set these icons in your derived renderer class how you want and then return that is returned by super.getTreeCellRendererComponent. As you set for every node before you render, you can easily have some different icon for the particular node.