tags:

views:

117

answers:

4

How can I change the icon of nodes and root in the JTree component of Swing?

+1  A: 

With a DefaultTreeCellRenderer use setClosedIcon, setOpenIcon and setLeafIcon.

Copied from How to Use Trees:

ImageIcon leafIcon = createImageIcon("images/middle.gif");
if (leafIcon != null) {
    DefaultTreeCellRenderer renderer = 
    new DefaultTreeCellRenderer();
    renderer.setLeafIcon(leafIcon);
    tree.setCellRenderer(renderer);
}
Peter Lang
+1  A: 

Sun's Tutorial on JTree has a section on how to subclass TreeCellRenderer to get nodes and text in a JTree.

willcodejavaforfood
A: 

If all you trying to do is to have different Icons for closed node, leaf and opened nodes, it is very straight forward.

//Create 3 icons private Icon customOpenIcon = new ImageIcon("images/my_open.gif"); private Icon customClosedIcon = new ImageIcon("images/my_closed.gif"); private Icon customLeafIcon = new ImageIcon("images/my_leaf.gif");

//Assuming you created your DefaultMutableTreeNode hierarchy DefaultMutableTreeNode rootNode = new... ... JTree tree = new JTree(rootNode );

DefaultTreeCellRenderer customRenderer = new DefaultTreeCellRenderer();
customRenderer.setOpenIcon(customOpenIcon);
customRenderer.setClosedIcon(customClosedIcon);
customRenderer.setLeafIcon(customLeafIcon);
tree.setCellRenderer(customRenderer );
ring bearer
i tried to use DefautTreeCellRenderer, but my class doesnt recognaize it, i use eclipse 3.2
samuel
A: 

Use your brain and javadocs... sights

aeaeraera