【发布时间】:2021-06-08 20:46:23
【问题描述】:
我写了这个简单的类来测试GridBagLayout。
我的范围是将一些对角线按钮放入面板中,使用网格包布局并设置gridx 和gridy,但我有一个奇怪的行为。
如果我将gridwidth = 2 放在按钮"2" 上,按钮"3" 将被绘制在标记为"2" 的按钮下。
我的课是一个简单的演示,但我不知道它有什么问题 猜猜为什么?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame {
private JPanel panel;
private JButton b1;
private JButton b2;
private JButton b3;
private JButton b4;
private JButton b5;
private JLabel label1;
public Test() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(Color.DARK_GRAY);
GridBagConstraints gbc = new GridBagConstraints();
b1 = new JButton("1");
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(b1, gbc);
b2 = new JButton("2");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
panel.add(b2, gbc);
gbc = new GridBagConstraints();
b3 = new JButton("3");
gbc.gridx = 2;
gbc.gridy = 2;
panel.add(b3, gbc);
gbc = new GridBagConstraints();
b4 = new JButton("4");
gbc.gridx = 3;
gbc.gridy = 3;
panel.add(b4, gbc);
gbc = new GridBagConstraints();
b5 = new JButton("5");
gbc.gridx = 1;
gbc.gridy = 4;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(b5, gbc);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(500, 400);
this.setSize(800, 300);
this.setTitle("Frame principale dell'applicazione");
this.setResizable(true);
getContentPane().add(panel, BorderLayout.CENTER);
this.setVisible(true);
}
public static void main(String[] args) {
Test mioFrame = new Test();
}
}
【问题讨论】:
-
当您将 1 添加到 gridy 时,gridx 应该回到零。你希望你的 GUI 看起来像什么? JButton 的正确布局是什么?
标签: java swing awt layout-manager gridbaglayout