Search code examples
javaswingjlabeljtree

How to display content by clicking on a JTree node


I have a problem with my JTree. My JTree shows (Music,Documents,Pictures,Videos and more) like the Windows Explorer. For example if I click on a node and this node is a folder that contains 5 (or more) images how can I display this 5 images in 5 single JLabels???


Solution

  • There are two ways you could approach this. The first (easier) would be to add your Images directly into the TreeModel, so that they are rendered by the DefaultTreeCellRenderer or an extension of it. The second, if you don't want to add the images to your TreeModel, would be to create a custom TreeCellRenderer which paints all of the images in one Component... But you risk running into issues over eventing / layout this way.

    Also, understand that JTree uses a Renderer, and that you can't actually add any components to the JTree, you can only render data items.