Win a copy of Practical SVG this week in the HTML/CSS/JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get Icon from JTree Node

 
Venkatesh Rajendran
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I would like to get Icon of a selected node from a JTree, it would be great if you could tell me some way to get the same.
Thanks in advance.
Regards,
Venkat
 
Stuart Friedberg
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DefaultTreeCellRenderer has closedIcon, openIcon, leafIcon to return
the relevant Icons.
So, get cellRenderer from your JTree, check that it is a subclass of DefaultTreeCellRenderer, then get the appropriate Icon. If the JTree has heavily customized rendering this solution won't work, and you will have to understand the details of the custom TreeCellRenderer implementation. But this works fine for all the usual look-and-feel JTree implementations.
 
Stuart Friedberg
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an alternative method. Like the previous method, it is limited to certain types of TreeCellRenderers, but it has some advantages (and disadvantages).
Do getCellRenderer() on your JTree, then getTreeCellRendererComponent(...)
on the result, passing all the same parameters that the JTree implementation will use for the row of interest. Check that the Component returned is a JLabel or AbstractButton. If so, call getIcon().
The advantage of this, over the previous method, is that it handles per-row customization of the renderer. The disadvantage is more complicated programming to set up getTreeCellRendererComponent correctly. Both techniques only work with certain (admittedly very common) tree cell renderer techniques.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!