2011-06-12 127 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?。再次,請閱讀教程以更好地理解它們。