关于布局管理器FlowLayout的思考:如何让FlowLayout自动换行(1)

 今天上午没什么事儿,打开CSDN的BBS,发现有人在问一个关于布局管理器的问题,请看:关于布局的一个问题 。说实话,开始我并不相信楼主说的这句话“然后我在JPanel外面套了一个JScrollPane,却发现图片会一直往右边加,超出JPanel的宽度则出现横向的滚动条,与预想的效果相差较大。”

于是写下下面的代码:

 

[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 image;  
  8.     private JLabel label;  
  9.     private JButton button;  
  10.     private JPanel buttonPanel, imagePanel;  
  11.     private JScrollPane scrollPane;  
  12.     private Container container;  
  13.       
  14.     public SimpleTest(int xPixels, int yPixels){  
  15.         super("Add Image");   
  16.           
  17.         button = new JButton("Add Image");  
  18.         image = new ImageIcon("C:/1.jpg");  
  19.         imagePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 55));  
  20.         scrollPane = new JScrollPane(imagePanel);  
  21.               
  22.         button.addActionListener(new ActionListener(){  
  23.             public void actionPerformed(ActionEvent e){   
  24.                 label = new JLabel(image);  
  25.                 imagePanel.add(label);  
  26.                 validate();  
  27.             }  
  28.         });  
  29.   
  30.         buttonPanel = new JPanel(new GridLayout(15));  
  31.         buttonPanel.add(button);  
  32.           
  33.         container = getContentPane();  
  34.         container.setLayout(new GridLayout(21));    
  35.           
  36.         container.add(buttonPanel);  
  37.         container.add(scrollPane);  
  38.           
  39.         setSize(xPixels, yPixels);  
  40.         setVisible(true);  
  41.     }  
  42.       
  43.     public static void main(String[] args) {   
  44.         new SimpleTest(400400);  
  45.     }  
  46. }  

 

 

输出请看图:

输出图1


你可能感兴趣的:(java,职场,FlowLayout,休闲,JScrollPane换行)