确实如楼主所言,里面的图片一直都是横着排的。但是我记得是可以设置FlowLayout在适当的时候换行显示的。原因,我初步分析是因为JPanel对象在放到JScrollPane对象中之后,JPanel对象就具有了延展性,而FlowLayout布局管理器只有在第一排排满的情况下,才考虑换行的。所以现在的问题就变成了如何让流布局管理器知道在何时换行。

经过n次试验和思考,终于想到了一点:同时限制JPanel对象和JScrollPane对象的大小!请看下面的代码,也经过了一些设置,看上去更舒服了吧(稍微舒服点啊,毕竟这不是问题的关键,呵呵)。

 

[java]  view plain copy print ?
  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4.   
  5.   
  6. public class SimpleTest extends JFrame{  
  7.     private ImageIcon p_w_picpath;  
  8.     private JLabel label;  
  9.     private JButton button;  
  10.     private JPanel buttonPanel, p_w_picpathPanel;  
  11.     private JScrollPane scrollPane;  
  12.       
  13.     public SimpleTest(int xPixels, int yPixels){  
  14.         super("Add Image");   
  15.           
  16.         button = new JButton("Add Image");  
  17.         button.setPreferredSize(new Dimension(8025));  
  18.         button.setMargin(new Insets(0505));  
  19.           
  20.         p_w_picpath = new ImageIcon("C:/1.jpg");  
  21.         p_w_picpathPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 55));  
  22.         scrollPane = new JScrollPane(p_w_picpathPanel);  
  23.         p_w_picpathPanel.setPreferredSize(new Dimension(xPixels, yPixels));//这是关键的2句  
  24.         scrollPane.setPreferredSize(new Dimension(xPixels, yPixels));  
  25.               
  26.         button.addActionListener(new ActionListener(){  
  27.             public void actionPerformed(ActionEvent e){   
  28.                 label = new JLabel(p_w_picpath);  
  29.                 p_w_picpathPanel.add(label);  
  30.                 validate();  
  31.             }  
  32.         });  
  33.   
  34.         buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 00));  
  35.         buttonPanel.add(button);  
  36.           
  37.         add(buttonPanel, BorderLayout.NORTH);  
  38.         add(scrollPane, BorderLayout.CENTER);  
  39.           
  40.         setSize(xPixels, yPixels);  
  41.         setVisible(true);  
  42.     }  
  43.       
  44.     public static void main(String[] args) {   
  45.         new SimpleTest(320400);  
  46.     }  
  47. }  

 

 

修改之后的输出如下,不仅能够自动换行,而且在拉伸总窗体的时候,能再次自动排列:

 

输出图2 输出图3