我将一个JPanel添加到一个JScrollPane中,在设置JPanel的布局的时候,JPanel的组件不会自动换行?求分析问题出现在什么地方。代码如下:
//滚动面板__参数设置需要时添加滚动条
JScrollPane findStudentScrollPanel = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//面板大小
findStudentScrollPanel.setBounds((int)((WIDTH*0.04)/2),0,(int)(WIDTH*0.96), (int)(HEIGHT*0.15));
//添加组件的面板
JPanel myPanel = new JPanel();
myPanel.setLayout(new FlowLayout(FlowLayout.LEFT,250,5));
//组件准备
JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
JLabel label3 = new JLabel("label3");
JLabel label4 = new JLabel("label4"); myPanel.add(label1);
myPanel.add(label2);
myPanel.add(label3);
myPanel.add(label4);
//滚动面板内组件的设置
findStudentScrollPanel.setViewportView(myPanel);
//面板设置可见
findStudentScrollPanel.setVisible(true);
//面板添加到窗口
aJFrame.add(findStudentScrollPanel);

解决方案 »

  1.   

    panel也要设置大小的,否则它不会自动换行import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class TestFrame extends JFrame
    {
    public static void main(String[] args)
    {
    //滚动面板__参数设置需要时添加滚动条
    JScrollPane findStudentScrollPanel = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    //面板大小
    int WIDTH = 800;
    int HEIGHT = 600;
    findStudentScrollPanel.setBounds((int)((WIDTH*0.04)/2),0,(int)(WIDTH*0.96), (int)(HEIGHT*0.15));
    //添加组件的面板
    JPanel myPanel = new JPanel();
    myPanel.setLayout(new FlowLayout(FlowLayout.LEFT,250,5));
    /*
     * 还要给myPanel设置一下大小
     * 如下所示:
     */
    myPanel.setPreferredSize(new Dimension(findStudentScrollPanel.getWidth(), findStudentScrollPanel.getHeight()));
    //组件准备
    JLabel label1 = new JLabel("label1");
    JLabel label2 = new JLabel("label2");
    JLabel label3 = new JLabel("label3");
    JLabel label4 = new JLabel("label4"); myPanel.add(label1);
    myPanel.add(label2);
    myPanel.add(label3);
    myPanel.add(label4);
    //滚动面板内组件的设置
    findStudentScrollPanel.setViewportView(myPanel);
    //面板设置可见
    findStudentScrollPanel.setVisible(true);
    //面板添加到窗口
    //aJFrame.add(findStudentScrollPanel);
    JFrame frame = new JFrame();
    frame.setLayout(null);
    frame.add(findStudentScrollPanel);
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    }
      

  2.   

    设置JPanel大小的时候不能用setSize么?我用setSize设置好像没效果