简体   繁体   English

根据深度级别更改JTree节点图标

[英]Change JTree node icons according to the depth level

I'm looking for changing the different icons of my JTree (Swing) 我正在寻找改变我的JTree(Swing)的不同图标

The java documentation explains how to change icons if a node is a leaf or not, but that's really not what I'm searching. java文档解释了如果节点是否为叶子,如何更改图标,但这实际上不是我正在搜索的内容。

For me it doesn't matter if a node is a leaf or, I just want to change the icons if the node is in the first/2nd/3rd depth level of the three. 对我来说,如果一个节点是一个叶子,或者我只是想在节点处于三个节点的第一/第二/第三深度级别时更改图标。

As an alternative to a custom TreeCellRenderer , you can replace the UI defaults for collapsedIcon and expandedIcon : 作为自定义TreeCellRenderer的替代方法,您可以替换collapsedIconexpandedIcon的UI默认值:

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: TreeIcon只是Icon界面的一个实现:

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;
    }
}

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. 实现自定义TreeCellRenderer - 使用JLabel作为组件,并使用树中存储的Object数据设置其图标。 You may need to wrap the object to store its depth, etc. if the object is primitive (String for example) 如果对象是原始的(例如String),您可能需要包装对象以存储其深度等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM