1

我正在使用 GridBagLayout 通过以下代码放置我的 GUI 组件,希望组件在列中一个一个地放置,没有任何间隙:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestGUI extends JFrame{

    public TestGUI(){

        JPanel bigPanel = new JPanel(new GridBagLayout());
        JPanel panel_a = new JPanel();
        JButton btnA = new JButton("button a");
        panel_a.add(btnA);

        JPanel panel_b = new JPanel();
        JButton btnB = new JButton("button b");
        panel_b.add(btnB);

        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        c.weighty = 1D;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.NORTH;
        bigPanel.add(panel_a, c);

        c.gridx = 0;
        c.gridy = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        bigPanel.add(panel_b, c);

        this.add(bigPanel);
    }

    public static void main(String[] args) {

        TestGUI gui = new TestGUI();
        gui.setVisible(true);
        gui.pack();
    }
}

我希望面板将在列中一一显示。但现在我得到了这个: 在此处输入图像描述

因为我要在 bigPanel 中添加更多组件,并且需要对布局进行更多自定义,所以我需要使用 GridBagLayout 而不是其他布局。

4

1 回答 1

1

您需要添加一个额外的组件,以便它将填充剩余的可用空间并将两个按钮面板推到顶部。当您将添加更多组件时,您当然可以删除该组件。

另一个选项(不需要额外的组件)是weighty=1.0panel_band设置anchor=NORTH,但是当您添加更多组件时,您必须更改它。

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TestGUI extends JFrame {

    public TestGUI() {

        JPanel bigPanel = new JPanel(new GridBagLayout());
        JPanel panel_a = new JPanel();
        JButton btnA = new JButton("button a");
        panel_a.add(btnA);

        JPanel panel_b = new JPanel();
        JButton btnB = new JButton("button b");
        panel_b.add(btnB);

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1.0;
        bigPanel.add(panel_a, c);
        bigPanel.add(panel_b, c);
        c.weighty = 1.0;
        // Temporary panel to fill the rest of the bigPanel
        bigPanel.add(new JPanel(), c);
        this.add(bigPanel);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                TestGUI gui = new TestGUI();
                gui.pack();
                gui.setVisible(true);
            }
        });
    }
}
于 2012-11-08T09:39:48.960 回答