Change The icon of a certain Node in JTree?

一曲冷凌霜 提交于 2019-12-11 13:52:52

问题


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.



来源:https://stackoverflow.com/questions/14192424/change-the-icon-of-a-certain-node-in-jtree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!