简体   繁体   中英

How to add JLabel in a JPanel Vertically?

I'd like to add JLabels dynamically in a JPanel vertically like the image that I've attached. After loading all images, I need to select an image, then selected the image should appear in another JPanel. I am reading Images from an ArrayList which contains the paths.

I used Jpanel with GridLayout in a JScrollPane, but the result is not the same that I want.

This is the code that I've used to add Jlabels:

for(String file: files) {                   
                    JLabel JLabelPicture = new JLabel(new ImageIcon(file));
                    panel_images.add(JLabelPicture);
                }

在此处输入图片说明

I used Jpanel with GridLayout in a JScrollPane, but the result is not the same that I want.

A GridLayout will allow you to display the components vertically. When you create your panel you just use:

JPanel imagePanel = new JPanel( new GridLayout(0, 1) );

This will resize all the images to the same size.

Another option is to use a vertical BoxLayout . In this case you can use:

Box imagePanel = Box.createVerticalBox();

In this case the images will retain their preferred size.

In both case you add to the panel to a scroll pane which is added to your frame:

frame.add( new JScrollPane( imagePanel ) );

Read the Swing tutorial on Layout Managers for more information and working examples of each layout.

Edit:

after listing the images I need to select one of them,

Well where was that requirement in your original question. The complete requirement should be defined in the question so all the information is in one place for everybody to see.

So I would suggest you should be using a JList to display an Icon. Read the section from the Swing tutorial on How to Use Lists for more information.

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