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

标签 java swing icons jtree

我正在寻找更改我的 JTree (Swing) 的不同图标

Java 文档解释了如何在节点是否为叶子时更改图标,但这并不是我要搜索的内容。

对我来说,节点是不是叶子并不重要,或者我只想更改图标,如果节点在三个深度级别中的第一/第二/第三深度级别。

最佳答案

作为自定义 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 只是 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;
    }
}

关于java - 根据深度级别更改 JTree 节点图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4640818/

相关文章:

java - 为什么selector.select()总是返回0

java - 在 Java 中使用 Semaphore 和 Monitor 出现 IllegalMonitorException

java - JFileChooser 和 eclipse

java - JTextField无法在if语句java中使用输入

iPhone:主屏幕和 App Store 的图标不同

"main"线程的 Java 执行器

java - Dr java keylistener 帮助对象在按键释放后移动

c++ - 如何更改 .exe 中的图标(使用 C++ 的 App Wxwidgets)

android - 创建透视(android)应用程序图标

java - Spring webmvc 链接 viewresolvers 给出 BeanNotOfRequiredTypeException