确实如楼主所言,里面的图片一直都是横着排的。但是我记得是可以设置FlowLayout在适当的时候换行显示的。原因,我初步分析是因为JPanel对象在放到JScrollPane对象中之后,JPanel对象就具有了延展性,而FlowLayout布局管理器只有在第一排排满的情况下,才考虑换行的。所以现在的问题就变成了如何让流布局管理器知道在何时换行。
经过n次试验和思考,终于想到了一点:同时限制JPanel对象和JScrollPane对象的大小!请看下面的代码,也经过了一些设置,看上去更舒服了吧(稍微舒服点啊,毕竟这不是问题的关键,呵呵)。
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- public class SimpleTest extends JFrame{
- private ImageIcon p_w_picpath;
- private JLabel label;
- private JButton button;
- private JPanel buttonPanel, p_w_picpathPanel;
- private JScrollPane scrollPane;
- public SimpleTest(int xPixels, int yPixels){
- super("Add Image");
- button = new JButton("Add Image");
- button.setPreferredSize(new Dimension(80, 25));
- button.setMargin(new Insets(0, 5, 0, 5));
- p_w_picpath = new ImageIcon("C:/1.jpg");
- p_w_picpathPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
- scrollPane = new JScrollPane(p_w_picpathPanel);
- p_w_picpathPanel.setPreferredSize(new Dimension(xPixels, yPixels));//这是关键的2句
- scrollPane.setPreferredSize(new Dimension(xPixels, yPixels));
- button.addActionListener(new ActionListener(){
- public void actionPerformed(ActionEvent e){
- label = new JLabel(p_w_picpath);
- p_w_picpathPanel.add(label);
- validate();
- }
- });
- buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
- buttonPanel.add(button);
- add(buttonPanel, BorderLayout.NORTH);
- add(scrollPane, BorderLayout.CENTER);
- setSize(xPixels, yPixels);
- setVisible(true);
- }
- public static void main(String[] args) {
- new SimpleTest(320, 400);
- }
- }
修改之后的输出如下,不仅能够自动换行,而且在拉伸总窗体的时候,能再次自动排列:
转载于:https://blog.51cto.com/zhangchenguanga/784784