Change JTree node icons according to the depth level

后端 未结 2 1996
予麋鹿
予麋鹿 2020-11-30 12:56

I\'m looking for changing the different icons of my JTree (Swing)

The java documentation explains how to change icons if a node is a leaf or not, but that\'s really

相关标签:
2条回答
  • 2020-11-30 13:16

    Implement a custom TreeCellRenderer - use a JLabel for the component, and set its icon however you like using the data of the Object stored in the tree. You may need to wrap the object to store its depth, etc. if the object is primitive (String for example)

    http://download.oracle.com/javase/7/docs/api/javax/swing/tree/TreeCellRenderer.html http://www.java2s.com/Code/Java/Swing-JFC/TreeCellRenderer.htm

    0 讨论(0)
  • 2020-11-30 13:25

    As an alternative to a custom TreeCellRenderer, you can replace the UI defaults for collapsedIcon and expandedIcon:

    Icon expanded = new TreeIcon(true, Color.red);
    Icon collapsed = new TreeIcon(false, Color.blue);
    UIManager.put("Tree.collapsedIcon", collapsed);
    UIManager.put("Tree.expandedIcon", expanded);
    

    TreeIcon is simply an implementation of the Icon interface:

    class TreeIcon implements Icon {
    
        private static final int SIZE = 14;
        private boolean expanded;
        private Color color;
    
        public TreeIcon(boolean expanded, Color color) {
            this.expanded = expanded;
            this.color = color;
        }
    
        //@Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setPaint(color);
            if (expanded) {
                g2d.fillOval(x + SIZE / 4, y, SIZE / 2, SIZE);
            } else {
                g2d.fillOval(x, y + SIZE / 4, SIZE, SIZE / 2);
            }
        }
    
        //@Override
        public int getIconWidth() {
            return SIZE;
        }
    
        //@Override
        public int getIconHeight() {
            return SIZE;
        }
    }
    
    0 讨论(0)
提交回复
热议问题