将多个jPanels添加到jFrame

15

我想在一个JFrame中并排添加两个JPanel。这两个盒子是JPanel,外部盒子是JFrame enter image description here

我有以下代码。我有一个名为seatinPanel的类,它继承了JPanel,在这个类中我有一个构造函数和一个名为utilityButtons的方法,该方法返回一个JPanel对象。我希望utilityButtons JPanel在右侧显示。但是,我现在运行此代码时只会显示utilityButtons 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个回答

28

我建议使用最灵活的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);

然后将容器添加到您的框架组件中。


2
当我尝试这样做时,它会给我一个错误提示:BoxLayout无法共享。 - dave

5
你需要了解和学习Swing提供的布局管理器。在你的情况下,需要知道JFrame的contentPane默认使用BorderLayout,你可以将较大的中心JPanel添加到BorderLayout.CENTER,其他JPanel添加到BorderLayout.EAST。更多信息可以在这里找到:在容器中布置组件 编辑1 Andrew Thompson在你之前的帖子中已经向你展示了一些布局管理器的代码:为什么我的按钮没有显示?请再次阅读教程以更好地理解它们。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接