2011-08-02 29 views
1

我有3個JPanel,我想將它們全部放在一個JPanel中。我使用GridBagLayout作爲主面板。但只有一個面板被添加。爲什麼會這樣呢?無法將3個JPanel添加到主面板

gblayout=new GridBagLayout(); 
    gbc=new GridBagConstraints(); 
    panel1Customizer(); 
    panel2customizer(); 
    panel3Customizer(); 
    setLayout(gblayout); 
    gbc.fill=GridBagConstraints.HORIZONTAL; 
    gbc.anchor=GridBagConstraints.NORTHWEST; 
    gbc.weightx=1; 
    gbc.weighty=1; 
    gbc.gridheight=GridBagConstraints.REMAINDER; 
    add(panel1, gbc); 
    add(panel2, gbc); 
    gbc.gridwidth=GridBagConstraints.REMAINDER; 
    add(panel3, gbc); 

定製器方法是將項目添加到這些面板中的方法。

+0

此代碼工作正常,問題可能是在其他地方。 –

回答

1

我不確定,但我想你需要添加一個GridBagConstraints到你的GridBagLayout。嘗試看看這個網站獲得關於如何使用GridBagLayout的工作思路: link

或者,也許只是用另一種佈局爲您的JFrame,也許BorderLayout的或網格佈局安排您面板正確

1

你應該改變GBC。爲gridx和/或gbc.gridy是不同的每個小組

+1

其實這不是必需的,默認情況下組件被追加。 –

1

一定要仔細閱讀How to Use GridBagLayout,對於hereGridBagConstraints例子,改變你的gbc.fill=GridBagConstraints.HORIZONTAL;,如果你有JComponent's Size問題(一個或多個),然後添加setPreferedSize();例如

import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import javax.swing.*; 

public class GBLFillBoth extends JFrame { 
    private static final long serialVersionUID = 1L; 

    public GBLFillBoth() { 
    JPanel panel = new JPanel(); 
    GridBagLayout gbag = new GridBagLayout(); 
    panel.setLayout(gbag); 
    GridBagConstraints c = new GridBagConstraints(); 
    JButton btn1 = new JButton("One"); 
    c.fill = GridBagConstraints.BOTH; 
    //c.fill = GridBagConstraints.HORIZONTAL; 
    c.anchor=GridBagConstraints.NORTHWEST; 
    c.gridx = 0; 
    c.gridy = 0; 
    c.weightx = 0.5; 
    c.weighty = 0.5; 
    panel.add(btn1, c); 
    JButton btn2 = new JButton("Two"); 
    c.gridx++; 
    panel.add(btn2, c); 
    //c.fill = GridBagConstraints.BOTH; 
    JButton btn3 = new JButton("Three"); 
    c.gridx = 0; 
    c.gridy++; 
    c.gridwidth = 2; 
    panel.add(btn3, c); 
    add(panel); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    pack(); 
    setVisible(true); 
    } 

    public static void main(String[] args) { 
     GBLFillBoth gBLFillBoth = new GBLFillBoth(); 
    } 
} 
1

你可能會考慮使用MigLayout相反,代碼簡單得多:

panel1Customizer(); 
panel2customizer(); 
panel3Customizer(); 
setLayout(new MigLayout("fill, wrap 3")); 

add(panel1, "grow"); 
add(panel2, "grow"); 
add(panel3, "grow");