How can I change the icon of nodes and root in the JTree
component of Swing?
views:
117answers:
4
+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
2010-02-24 16:07:41
+1
A:
Sun's Tutorial on JTree has a section on how to subclass TreeCellRenderer to get nodes and text in a JTree.
willcodejavaforfood
2010-02-24 16:08:57
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
2010-02-24 16:32:02
i tried to use DefautTreeCellRenderer, but my class doesnt recognaize it, i use eclipse 3.2
samuel
2010-02-24 16:50:39