Java GridBagLayout – 如何将我的组件无间隙地逐个定位?

我正在使用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而不是其他布局。

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

另一个选项(不需要额外的组件)就是为panel_banchor=NORTH设置panel_b weighty=1.0 ,但是当你添加更多的组件时你必须改变它。

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