GridBagLayout交错按钮

时间:2013-02-08 00:56:17

标签: java swing gridbaglayout

如何让GridBagLayout的列均匀分布,以便我可以将按钮放在标准的交错计算机键盘上?我正在谈论类似这样的事情,其中​​的按钮彼此之间并不完全排列:QWERTY Keyboard

最小功能性工作示例(注意交错的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之间。我该怎么做?

1 个答案:

答案 0 :(得分:0)

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