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

标签 java swing jframe jtree

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

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

...

等等。我尝试了几种来源,其中一种有点工作,但它搞乱了树事件,所以没有雪茄。提前致谢。

根据某人的要求:

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

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

最佳答案

I don't want the sub-roots to show, just the nodes.

您的 getTreeCellRendererComponent() 实现应该会看到一个经过正确调节的boolean leaf 参数,您可以使用该参数,如图 here .

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

关于java - 如何为 JTree 上的各个节点设置自定义图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15374331/

相关文章:

java - 每秒显示随机 Line2D.Double 的屏幕保护程序(JFrame 内的 JPanel)

java - 当帧捕捉到屏幕左侧或右侧时具有事件的监听器

java - 删除最老条目

java - 在没有 try-catch 的情况下验证整数或字符串

java - Java中如何获取void函数的值?

Java:即使我在后台运行游戏时如何保持我的应用程序正常运行

java - getItem 和 getSelectedItem 之间的区别

java - 将 Spring-Security PasswordEncoder 与默认身份验证提供程序一起使用?

java - JSplitPane 组件不聚焦

java - 如何将 JXTaskPane 设置为默认折叠?