将多个jPanel添加到jFrame

我想并排添加两个jPanel到JFrame。 两个框是jpanels,外框是jframe 在此处输入图像描述

我有这些代码行。 我有一个名为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); } 

我推荐的最灵活的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); 

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

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

编辑1
Andrew Thompson已经在你上一篇文章的代码中向你展示过布局管理器: 为什么我的按钮没有出现? 。 再次,请阅读教程以更好地理解它们。