1
votes

I'm having some issues with my GridBagLayout. I have created a JPanel (in this case it's called mainPanel), whose layout has been set to GridBagLayout. I have specified the constraints for each JButton, and added the constraints to each button. Now, when I run my code, the buttons are always next to each other, irrespective of the gridx/gridy value that I indicate in the constraints. Furthermore, the buttons are always at the center of the JFrame, when I would like one button to appear at the top right, top left, and south.

import javax.swing.*;
import java.awt.*;

public class test {
public static void main (String[] args) {
    myJFrame test = new myJFrame();
    }
}

class myJFrame extends JFrame {
   public myJFrame () {
      setSize(500,500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      mainPanel myPanel = new mainPanel();
      add(myPanel);

     setVisible(true);
 }
}

class mainPanel extends JPanel {
    public mainPanel(){
       setLayout(new GridBagLayout());
       GridBagConstraints c = new GridBagConstraints();

        c.anchor =      GridBagConstraints.NORTHWEST;
        c.gridx =       1000;
        c.gridy=        1;
        add(new JButton("1"),c);

        c.anchor =      GridBagConstraints.NORTHEAST;
        c.gridx =       100;
        c.gridy=        1;
        add(new JButton("2"),c);

        c.anchor =      GridBagConstraints.SOUTH;
        c.gridx =       200;
        c.gridy=        1;
        add(new JButton("3"),c);
   }
}

This is what i get when i run the code

1

1 Answers

0
votes

Now, when I run my code, the buttons are always next to each other, irrespective of the gridx/gridy value that I indicate in the constraints.

Correct, you can't just specify random cells. A component must be located in each cell.

Furthermore, the buttons are always at the center of the JFrame,

Yes, this is the default behaviour if you don't specify a weightx/weighty constraint.

Read the section from the Swing tutorial on How to Use GridBagLayout for more information on constraints and working examples.

Why are you picking random x locations like 100, 200, 1000? Maybe a horizontal BoxLayout would be a better layout manager. You can add the components and then add space between them:

panel.add( button1 );
panel.add( Box.createHorizonalStrut(100);
panel.add( button2 );
panel.add( Box.createHorizonalStrut(200);

Or maybe use a FlowLayout and specify the "gap" between each component.