1

我有 3 个 JPanel,我想将它们全部放在一个 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);

定制器方法是将项目添加到这些面板中的方法。

4

4 回答 4

1

我不确定,但我认为您需要将 GridBagConstraints 添加到您的 GridBagLayout。尝试查看此站点以了解如何使用 GridBagLayout: 链接

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

于 2011-08-02T07:41:25.507 回答
1

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

于 2011-08-02T07:44:30.793 回答
1

您必须阅读如何使用 GridBagLayout此处的示例和GridBagConstraintsgbc.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();
  }
}
于 2011-08-02T07:46:06.363 回答
1

您可以考虑改用 MigLayout,代码要简单得多:

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

add(panel1, "grow");
add(panel2, "grow");
add(panel3, "grow");
于 2011-08-02T07:50:30.600 回答