From: stormreaver
Written: 2009-02-11 08:36:10.355298
Subject: Showing A Different Icon In Each Node Of A JTree

There are occasions when you want to display a JTree, and have each node represent something unique. In fact, this is the vast majority of use-cases for a JTree (there's little reason to use a tree structure for anything else).

The stock JTree has a couple annoying deficiencies: it only has a single column in its tree, and it doesn't allow you to set different icons for each row. The latter is one of those seemingly simple things that Java makes harder than it needs to be. On the bright side, it's not as hard as most tutorials make it. I'll show you the minimal steps you need to take in order to accomplish this.

The JTree shows its tree data via a pluggable cell renderer, which provides for great flexibility. This is great, because you're going to have to take advantage of that flexibility. Here's the short and sweet explanation: you have to create your own cell renderer that decides which icons to display.


FeeRenderer is the name I used for my class, but you can call it anything you want.

FeeNode is a class I created to associate a DefaultMutableTreeNode used in the JTree with the icon I want to display. Use whatever association mechanism you want.

Here's the code you need:

public class FeeRenderer extends DefaultTreeCellRenderer
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean bSelected, boolean bExpanded, boolean bLeaf, int nRow, boolean bFocus)
super.getTreeCellRendererComponent(tree, value, bSelected, bExpanded, bLeaf, nRow, bFocus);

if (bLeaf && m_lstFees != null && m_lstFees.size() > 0)
FeeNode node = findNode((DefaultMutableTreeNode) value);

if (node != null)
return this;

In this example, I display a different icon for each leaf node. The findNode() function call, in this example, searches a list that contains the node reference and the corresponding icon to display for that node. You can use whatever mechanism you like for associating icons with nodes.

If findNode() returns a node, it calls setIcon() which tells the cell renderer which icon to display. This icon will be displayed for subsequent nodes, too, unless you change it. For this reason, I set a null icon if findNode() returns null.

To enable this cell renderer, you merely need to call [your_jtree_object].setCellRenderer([your_renderer_object]) when you create your JTree.

That's all there is to it. If you have any questions, feel free to ask (you'll need to register an account in order to reply).
You must register an account before you can reply.