无法将3个JPanel添加到主面板

我有3个JPanels,我想将它们全部放在一个JPanel中。 我使用GridBagLayout作为主面板。 但是只添加了一个面板。 为什么会这样?

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); 

自定义程序方法是将项添加到这些面板中的方法。

我不确定,但我认为你需要在GridBagLayout中添加GridBagConstraints。 试试看这个网站,了解如何使用GridBagLayout: link

或者也许只是为您的JFrame使用另一个布局,可能是BorderLayout或GridLayout来正确排列您的面板

您应该将gbc.gridx和/或gbc.gridy更改为每个面板的不同

你必须阅读如何使用GridBagLayout , 这里的例子和GridBagConstraints ,改变你的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(); } } 

您可以考虑使用MigLayout,代码更简单:

 panel1Customizer(); panel2customizer(); panel3Customizer(); setLayout(new MigLayout("fill, wrap 3")); add(panel1, "grow"); add(panel2, "grow"); add(panel3, "grow");