I need to be able to set icons for the JTree individual nodes. For example, I have a JTree and I need the nodes to have custom icons that help represent what they are.
- (wrench icon) Settings
- (bug icon) Debug
- (smiley face icon) Fun Stuff
...
And so on. I have tried several sources and got one somewhat working, but it messed up the tree events so, no cigar. Thanks in advance.
As someone requested:
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;
}
}
Then where it's initialized:
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);
}
And this works, it's just I don't want the sub-roots to show, just the nodes. Also, this code makes it so that the item won't highlight when you click it.