2

如何让 GridBagLayout 的列均匀分布,以便我可以像在标准交错计算机键盘上一样放置按钮?我说的是这样的事情,其中​​按钮彼此不太对齐:QWERTY键盘

最小功能工作示例(注意交错gridxgridwidth值):

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 之间。我该怎么做?

4

1 回答 1

0

您是否考虑在不透明度设置为 0 的第二行的开头添加一个虚拟项目?只需将其宽度设置为您需要的确切标签。

于 2013-02-08T04:06:39.007 回答