将多个jPanel添加到jFrame

时间:2011-06-12 23:21:23

标签: java swing jpanel layout-manager

我想将两个jPanel并排添加到JFrame中。两个框是jpanels,外框是jframe enter image description here

我有这些代码行。我有一个名为seatinPanel的类,它扩展了JPanel,在这个类中我有一个构造函数和一个名为utilityButtons的方法,它返回一个JPanel对象。我希望utilityButtons JPanel在右侧。我这里的代码只在运行时显示utillityButtons JPanel。

public guiCreator()
    {
        setTitle("Passenger Seats");
        //setSize(500, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Container contentPane = getContentPane();

        seatingPanel seatingPanel1 = new seatingPanel();//need to declare it here separately so we can add the utilityButtons
        contentPane.add(seatingPanel1); //adding the seats
        contentPane.add(seatingPanel1.utilityButtons());//adding the utility buttons

        pack();//Causes this Window to be sized to fit the preferred size and layouts of its subcomponents
        setVisible(true);  
    }

2 个答案:

答案 0 :(得分:27)

我建议最灵活的LayoutManager是BoxLayout

您可以执行以下操作:

JPanel container = new JPanel();
container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));

JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();

//panel1.set[Preferred/Maximum/Minimum]Size()

container.add(panel1);
container.add(panel2);

然后将容器添加到框架组件的对象。

答案 1 :(得分:5)

您需要阅读并了解Swing必须提供的布局管理器。在您的情况下,有助于知道JFrame的contentPane默认使用BorderLayout,您可以添加更大的中心JPanel BorderLayout.CENTER和另一个JPanel BorderLayout.EAST。更多信息可以在这里找到:Laying out Components in a Container

编辑1
Andrew Thompson已经在你上一篇文章的代码中向你展示了布局管理器:why are my buttons not showing up?。再次,请阅读教程以更好地理解它们。