JPanel中的组件不会自动更改行

时间:2011-10-18 10:09:50

标签: java swing jpanel flowlayout

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.*;

public class FileCutter
{
    public static void main(String[] args)
    {
        CutterWindow cw = new CutterWindow();
        cw.setResizable(false);
        cw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        cw.setVisible(true);
    }
}

class CutterWindow extends JFrame
{
    private JTabbedPane tabbedPane = new JTabbedPane();

    public static final int DEFAULT_WIDTH = 470;
    public static final int DEFAULT_HEIGHT = 480;
    public CutterWindow()
    {
        this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        tabbedPane.add("File Cut",new FileCutPanel());
        this.add(tabbedPane);
    }

}

class FileCutPanel extends JPanel
{   
    private JLabel lblFileName =  new JLabel("File Name:");
    private JTextField txtFileName = new JTextField();
    private JLabel lblFileSize = new JLabel("File Size:");
    private JTextField txtFileSize = new JTextField();
    private JButton btnViewFiles = new JButton("...");

    private JPanel panelSelectOperatingFile = new JPanel();

    public FileCutPanel()
    {   
        panelSelectOperatingFile.setLayout(new FlowLayout());
        panelSelectOperatingFile.add(lblFileName);
        txtFileName.setColumns(20);
        txtFileName.setEditable(false);
        panelSelectOperatingFile.add(txtFileName);
        panelSelectOperatingFile.add(btnViewFiles);
        panelSelectOperatingFile.add(lblFileSize);
        panelSelectOperatingFile.add(txtFileSize);
        txtFileSize.setColumns(20);
        txtFileSize.setEditable(false);

        this.add(panelSelectOperatingFile);
    }
}

结果是panelSelectOperatingFile面板中的五个组件位于同一行并超出了窗口的宽度。我知道JPanel的默认布局是flowlayout,我预计当前一行中没有空格时,组件将被放入下一行。我试图弄清楚问题,但我不能

1 个答案:

答案 0 :(得分:2)

请勿使用panelSelectOperatingFile面板。只需将您的组件添加到您要扩展的JPanel

您无法嵌套FlowLayouts。原因如下:

Oracle FlowLayout Tutorial