我需要能够为 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);
}
这行得通,只是我不想显示子根,只显示节点。此外,此代码使该项目在您单击它时不会突出显示。