samuel
samuel

Reputation: 275

JTree component in java swing

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

Upvotes: 1

Views: 778

Answers (3)

ring bearer
ring bearer

Reputation: 20803

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 );

Upvotes: 0

willcodejavaforfood
willcodejavaforfood

Reputation: 44103

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

Upvotes: 1

Peter Lang
Peter Lang

Reputation: 55614

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);
}

Upvotes: 2

Related Questions