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