【发布时间】:2021-03-15 20:24:48
【问题描述】:
我尝试使用 GridBagConstraints 将组件(例如:按钮)放置在容器中。但我发现元素之间有一个空白区域。我尝试修改各种参数,但找不到解决方案。
我想删除这个空白区域(例如,按钮 8 应该在按钮 4、6、7 的右侧)。
谢谢
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayout8Button {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints gbc1 = new GridBagConstraints();
GridBagConstraints gbc2 = new GridBagConstraints();
GridBagConstraints gbc3 = new GridBagConstraints();
GridBagConstraints gbc4 = new GridBagConstraints();
GridBagConstraints gbc5 = new GridBagConstraints();
GridBagConstraints gbc6 = new GridBagConstraints();
GridBagConstraints gbc7 = new GridBagConstraints();
GridBagConstraints gbc8 = new GridBagConstraints();
JButton button1 = new JButton("1");
gbc1.anchor = GridBagConstraints.NORTHWEST;
gbc1.gridx = 0;
gbc1.gridy = 0;
gbc1.gridwidth = 1;
gbc1.gridheight = 2;
button1.setPreferredSize(new Dimension(46, 82));
pane.add(button1, gbc1);
JButton button2 = new JButton("2");
gbc2.anchor = GridBagConstraints.NORTHWEST;
gbc2.gridx = 1;
gbc2.gridy = 0;
gbc2.gridwidth=1;
gbc2.gridheight=1;
button2.setPreferredSize(new Dimension(118, 41));
pane.add(button2, gbc2);
JButton button3 = new JButton("3");
gbc3.anchor = GridBagConstraints.NORTHWEST;
gbc3.gridx = 1;
gbc3.gridy = 1;
gbc3.gridwidth=1;
gbc3.gridheight=1;
button3.setPreferredSize(new Dimension(118, 41));
pane.add(button3, gbc3);
JButton button4 = new JButton("4");
gbc4.anchor = GridBagConstraints.NORTHWEST;
gbc4.gridx = 2;
gbc4.gridy = 0;
gbc4.gridwidth = 2;
gbc4.gridheight = 2;
button4.setPreferredSize(new Dimension(164, 82));
pane.add(button4, gbc4);
JButton button5 = new JButton("5");
gbc5.anchor = GridBagConstraints.NORTHWEST;
gbc5.gridx = 0;
gbc5.gridy = 2;
gbc5.gridwidth=3;
gbc5.gridheight=2;
button5.setPreferredSize(new Dimension(246, 82));
pane.add(button5, gbc5);
JButton button6 = new JButton("6");
gbc6.anchor = GridBagConstraints.NORTHWEST;
gbc6.gridx = 3;
gbc6.gridy = 2;
gbc6.gridwidth=1;
gbc6.gridheight=1;
button6.setPreferredSize(new Dimension(82, 41));
pane.add(button6, gbc6);
JButton button7 = new JButton("7");
gbc7.anchor = GridBagConstraints.NORTHWEST;
gbc7.gridx = 3;
gbc7.gridy = 3;
gbc7.gridwidth=1;
gbc7.gridheight=1;
button7.setPreferredSize(new Dimension(82, 41));
pane.add(button7, gbc7);
JButton button8 = new JButton("8");
gbc8.anchor = GridBagConstraints.NORTHWEST;
gbc8.gridx = 4;
gbc8.gridy = 0;
gbc8.gridwidth=1;
gbc8.gridheight=4;
button8.setPreferredSize(new Dimension (41, 164));
pane.add(button8, gbc8);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("GridBagLayout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
});
}
}
【问题讨论】:
标签: java swing layout-manager gridbaglayout