根据深度级别更改JTree节点图标 [英] Change JTree node icons according to the depth level

查看:132
本文介绍了根据深度级别更改JTree节点图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

java文档解释了如果节点是否为叶子,如何更改图标,但这真的不是我正在搜索的内容。

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.

对我而言,如果一个节点是一个叶子,或者我只是想改变节点的图标处于三者的第一/第二/第三深度水平。

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.

推荐答案

作为自定义 TreeCellRenderer ,您可以替换 collapsedIcon expandedIcon 的UI默认值:

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 只是<的实现code>图标界面:

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

这篇关于根据深度级别更改JTree节点图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆