繁体   English   中英

如何为JTree上的各个节点设置自定义图标?

[英]How to set custom icons for individual nodes on a JTree?

我需要能够为JTree单个节点设置图标。 例如,我有一个JTree,我需要节点具有自定义图标来帮助表示它们是什么。

  • (扳手图标)设置
  • (错误图标)调试
  • (笑脸图标)有趣的东西

...

等等。 我尝试了几种来源,但其中一些运作正常,但它弄乱了树木事件,所以没有雪茄。 提前致谢。

根据某人的要求:

class Country {
    private String name;
    private String flagIcon;

    Country(String name, String flagIcon) {
        this.name = name;
        this.flagIcon = flagIcon;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFlagIcon() {
        return flagIcon;
    }

    public void setFlagIcon(String flagIcon) {
        this.flagIcon = flagIcon;
    }
}

class CountryTreeCellRenderer implements TreeCellRenderer {
    private JLabel label;

    CountryTreeCellRenderer() {
        label = new JLabel();
    }

    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
        Object o = ((DefaultMutableTreeNode) value).getUserObject();
        if (o instanceof Country) {
            Country country = (Country) o;
            label.setIcon(new ImageIcon(country.getFlagIcon()));
            label.setText(country.getName());
        } else {
            label.setIcon(null);
            label.setText("" + value);
        }
        return label;
    }
}

然后在哪里初始化:

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Countries");
    DefaultMutableTreeNode asia = new DefaultMutableTreeNode("General");
    Country[] countries = new Country[]{
            new Country("Properties", "src/biz/jabaar/lotus/sf/icons/page_white_edit.png"),
            new Country("Network", "src/biz/jabaar/lotus/sf/icons/drive_network.png"),
    };

    for (Country country : countries) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(country);
        asia.add(node);
    }

这行得通,只是我不想显示子根目录,而只显示节点。 另外,此代码可以使该项目在您单击时不会突出显示。

我不希望显示子根目录,而仅显示节点。

你的实现的getTreeCellRendererComponent()应该会看到一个适当调理boolean leaf如图所示,您可以使用参数在这里

if (o instanceof Country && leaf) { ... }

暂无
暂无

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

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