如何让 GridBagLayout 的列均匀分布,以便我可以像在标准交错计算机键盘上一样放置按钮?我说的是这样的事情,其中按钮彼此不太对齐:
最小功能工作示例(注意交错gridx
和gridwidth
值):
import java.awt.*;
import javax.swing.*;
public class Keyboard extends JFrame {
public static void main(String args[]) {
(new Keyboard()).setVisible(true);
}
public Keyboard() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 300);
setLayout(new GridBagLayout());
JButton[] b = new JButton[5];
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.ipady = 20;
c.weightx = 0.5;
c.weighty = 0.5;
c.insets = new Insets(2, 2, 2, 2);
b[0] = new JButton("A");
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 2;
add(b[0], c);
b[1] = new JButton("B");
c.gridx = 2;
c.gridy = 0;
c.gridwidth = 2;
add(b[1], c);
b[2] = new JButton("C");
c.gridx = 4;
c.gridy = 0;
c.gridwidth = 2;
add(b[2], c);
b[3] = new JButton("D");
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
add(b[3], c);
b[4] = new JButton("E");
c.gridx = 3;
c.gridy = 1;
c.gridwidth = 2;
add(b[4], c);
}
}
我希望按钮 D 的右边框一直到 A 和 B 之间的中间,而 E 应该在 B 和 C 之间。我该怎么做?