Pradeep's Blog

Google

Monday, May 29, 2006

Customizing JTree

The default look and feel that the JTree provides might not be reasonable for certain applications. For example, the tree structure in eclipse has its own custom icons to represent different things (packages, java files, text files, etc). Let’s have a look at how to customise the JTree, so that we can get to a level of customization as shown below.

There are actually two ways of doing the customization. The first method is straight-forward and this is all that you have to do:

1. Create the tree structure.
2. Create an object of DefaultTableCellRenderer and set the icons as shown below:


ImageIcon customLeafIcon = new ImageIcon(“class.gif”);
DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer(); renderer.setLeafIcon(customLeafIcon);
tree.setCellRenderer(renderer);

The tree would look something like this now.

Similarly you can change lots of other things. For more details have a look at the API. There are some drawbacks to this method such as, all leaf node icons being the same. So for those of you who would like to tweak a bit more, method two would serve as the better alternative.


The second method is not as simple as the first one. This is what you have to do.

1. Create the tree structure.
2. Create a class that extends the DefaultTableCellRenderer class.
3. Override the method getTreeCellRendererComponent
4. Do all the customization in this method.
5. Create an object of the class that we just created, and set it as the new tree cell renderer.

TreeRenderer renderer = new TreeRenderer();

tree.setCellRenderer(renderer);

The code for the class that extends DefaultTableCellRenderer would look something like this:

And the resulting tree would look something like this.


1 Comments:

  • I say briefly: Best! Useful information. Good job guys.
    »

    By Anonymous Anonymous, at 7:53 PM  

Post a Comment

<< Home