Johnathan Allado
Johnathan Allado

Reputation: 33

How does gridwidth and gridheight work (Java guid GridBagLayout)?

I made 5 simple buttons to see how GridBagLayout constraints work, and got them set up like a cross. And I attempted to try out gridwidth for north, gbc.gridwidth = 2; (Since default is 0, then 1 and 2, which are 3 columns) to be exact. Isn't it supposed to take up 3 columns across the x axis of where North button stands? But when you run it, buttons get all overlapped. Please help explain what the problem is? Thank you

    JPanel jp = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();

    JButton jb1 = new JButton("North");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
    jp.add(jb1, gbc);

    JButton jb2 = new JButton("West");
    gbc.gridx = 0;
    gbc.gridy = 1;
    jp.add(jb2, gbc);

    JButton jb3 = new JButton("Center ");
    gbc.gridx = 1;
    gbc.gridy = 1;
    jp.add(jb3, gbc);

    JButton jb4 = new JButton("East");
    gbc.gridx = 2;
    gbc.gridy = 1;
    jp.add(jb4, gbc);

    JButton jb5 = new JButton("South");
    gbc.gridx = 1;
    gbc.gridy = 2;
    jp.add(jb5, gbc);

    add(jp);

    setVisible(true);

Upvotes: 3

Views: 7455

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

The core problem is, you haven't reset the constraints...

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits
jp.add(jb1, gbc);

JButton jb2 = new JButton("West");
// Still using the gridwidth value from before...
gbc.gridx = 0;
gbc.gridy = 1;
jp.add(jb2, gbc);

This means that the value for gridwidth is still set to 2 for ALL the other controls...

Try adding gbc = new GridBagConstraints(); after you've added jb1.

Also, for some reason, gridwidth is not zero indexed, it starts at 1, so you probably want to use 3 instead...

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
jp.add(jb1, gbc);

gbc = new GridBagConstraints();
JButton jb2 = new JButton("West");
gbc.gridx = 0;
gbc.gridy = 1;
jp.add(jb2, gbc);

Now, I could be wrong, but you seem to be trying to make the north button control the entire upper row, something like...

Fill

For which you'll need something like...

JButton jb1 = new JButton("North");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits
gbc.fill = GridBagConstraints.HORIZONTAL;
jp.add(jb1, gbc);

As well...

Upvotes: 5

Related Questions