简体   繁体   中英

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???

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.

Ok I got it with the following code you´ll get the path of the node where you clicked...

MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { TreePath selPath=MyTree.getPathForLocation(e.getX(), e.getY()); // <--- this was the part I searched for!

        System.out.println(selPath);

         if(selPath != null) {
             if(e.getClickCount() == 1) {
                mySingleClick(selPath);

             }
             else if(e.getClickCount() == 2) {
                //myDoubleClick(selPath);
             }
         }
     }

    private void mySingleClick(TreePath selPath) {

// do whatever

    }
};
        MyTree.addMouseListener(ml);

with this I get the path and now I can use the path to fill my JLabels with Images.

Yes, use nested JLabel with BoxLayout in the container label:

JLabel mycontainer = new JLabel();
container.setLayout(new BoxLayout(mycontainer, BoxLayout.X_AXIS));
JLabel icon1Label = new JLabel();
JLabel icon2Label = new JLabel();
icon1Label.setIcon(icon1);
icon2Label.setIcon(icon2);
mycontainer.add(icon1Label);
mycontainer.add(icon2Label);

I have shown you how to store two images you can use different layouts to store more than one image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM