2011-06-12 137 views
11

我想将两个jPanel并排添加到JFrame中。两个盒子是jpanels,外盒子是一个jframe enter image description here将多个jPanel添加到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); 
    } 

回答

26

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

再加入容器反对你的框架组件。

+0

当我尝试这样做时,它给了我这个错误BoxLayout不能共享 – dave 2011-06-12 23:52:39

+0

@dave:对不起,我的错。我现在编辑我的答案。 – Heisenbug 2011-06-12 23:58:56

+0

感谢它现在工作 – dave 2011-06-13 00:06:34

5

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

编辑1
安德鲁·汤普森已经显示出你的布局管理器了一下他的代码在以前的帖子在这里:why are my buttons not showing up?。再次,请阅读教程以更好地理解它们。