Customizing JTree
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: