Search code examples
javaswinggridbaglayout

GridBagLayout staggered buttons


How do I get the columns for GridBagLayout to be spaced out evenly so that I can place buttons like they are on a standard staggered computer keyboard? I'm talking about something like this, where the buttons don't quite line up with each other: QWERTY Keyboard

Minimal functional working example (notice the staggered gridx and gridwidth values):

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);
    }
}

I want the right border of button D to go all the way to halfway in between A and B, while E should be between B and C. How do I do this?


Solution

  • Have you considered adding in a dummy item to the begining of the second row that has its opacity set to 0? Just set it's width to the exact tabbing you need.