Link to home
Start Free TrialLog in
Avatar of ragnar
ragnar

asked on

Customizing leaves of a JTree

I am constructing a JTree using JDK1.2 on Windows NT and would like to customize the look of individuals terminal nodes (leaves).  The application I'm developing compares two databases, represents their meta data in a tree format and visually identifies differences between them.

As an example, I want a node present in the one tree but not present in the other, to be have a different icon and color.  I know that I can change all the leaf icons by doing:

UIManager.put("Tree.leafIcon", new ImageIcon("icon.gif"));

This doesn't cut it though... I want to be able to change the icon on a specific leaf, not all of them.  I've looked for how to change the Font of the leaf, but I'm a little vague on this.  Again, I want to set the font (rather, color of the font) on a particular leaf, not all of them.

The general nature of my code is that I have a JFrame, with a SplitPane (horizontal) with two ScrollPanes (one in each split) and a JTree in each ScrollPane.  I've been creating node leaves with the following syntax:

node = new DefaultMutableTreeNode("name of leaf");
treeModel.insertNodeInto(node, parentNode, 0);

Just to be clear, here is a visual idea of what i'm after:

* root
  * leaf
  * different leaf <--different icon and font
  * leaf
  * leaf

Sample code would be great, or if you know that what I want to do can't be done, that is helpful too.  Many thanks in advance!
Avatar of Hans_Klose
Hans_Klose

You will have to implement the TreeCellRenderer
 interface
OR you could try to  override methods in javax.swing.tree.DefaultTreeCellRenderer.

then just  call (JTree)setCellRenderer(TreeCellRenderer yourRenderer) this Sets the TreeCellRenderer that will be used to draw each cell.

there is sample TreeCellRenderer in the SampleTree example that comes with Swing (it's not very simple one)

you can see another example (not too basic one too) at
https://www.experts-exchange.com/topics/comp/lang/java/Q.10099678
"JTree + Renderer + Editor"

if you need more help (and probably a piece of source code) - post a comment here or contact me at heyhey@nettaxi.com

best regards
  heyhey
Avatar of ragnar

ASKER

Hans_Klose,

I'm sorry, but I have to reject your answer as part of my request was some piece of code that would show the answer.  I knew that i needed to use a renderer, but for 300 points i was looking for something a bit more specific.
ASKER CERTIFIED SOLUTION
Avatar of heyhey_
heyhey_

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial