我需要能够为 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/