我需要能够为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);
}
这是有效的,只是我不希望子根显示,只是节点。此外,此代码使得该项目在您单击时不会突出显示。
答案 0 :(得分:1)
我不希望子根显示,只是节点。
您对getTreeCellRendererComponent()
的实施应该会看到一个条件适当的boolean leaf
参数,您可以按照here使用该参数。
if (o instanceof Country && leaf) { ... }