简体   繁体   English

如何在JPanel中垂直添加JLabel?

[英]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. 我想在JPanel中动态添加JLabel,就像我附加的图像一样。 After loading all images, I need to select an image, then selected the image should appear in another JPanel. 加载所有图像之后,我需要选择一个图像,然后选择的图像应出现在另一个JPanel中。 I am reading Images from an ArrayList which contains the paths. 我正在从包含路径的ArrayList中读取图像。

I used Jpanel with GridLayout in a JScrollPane, but the result is not the same that I want. 我在JScrollPane中将Jpanel与GridLayout一起使用,但是结果与我想要的不一样。

This is the code that I've used to add Jlabels: 这是我用来添加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. 我在JScrollPane中将Jpanel与GridLayout一起使用,但是结果与我想要的不一样。

A GridLayout will allow you to display the components vertically. GridLayout将允许您垂直显示组件。 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 . 另一种选择是使用垂直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. 阅读有关布局管理器的Swing教程,以获取更多信息和每个布局的工作示例。

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. 因此,我建议您应该使用JList来显示图标。 Read the section from the Swing tutorial on How to Use Lists for more information. 阅读Swing教程中有关如何使用列表的部分, 获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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