Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting GridBagLayout from top left corner in Java Swing

I'm new to Java Swing and I have been struggling to start the GridBagLayout from top left corner so that c.gridx=0 c.gridy=0 will put my object on the top left corner.

I'd appreciate if you could help me by telling what I need to do after this point:

    JPanel panel = new JPanel(new GridBagLayout());
    frame.add(panel);
    GridBagConstraints c = new GridBagConstraints();

I know that I have to use NORTHWEST or FIRST_LINE_START constants, but I don't know how. I tried to do it this way' but it did not realize the constants.

    frame.getContentPane().add(panel, BorderLayout.NORTHWEST);

Thanks for your help.

like image 538
Emir Avatar asked Jun 15 '11 20:06

Emir


2 Answers

if you want the grid to go all the way to the top, simply set all your weighty = 0 until the last item, set it to any number greater than 0, it will effectively push the rest of the buttons to the top.

Don't forget to also increment your button's gridy value.

Otherwise it will be centered. (the same can be done using gridx and weightx value if you arent using the c.fill = GridBagConstraints.HORIZONTAL property.)

like image 170
Jeremie D Avatar answered Nov 15 '22 18:11

Jeremie D


Read the section from the Swing tutorial on How to Use GridBagLayout. The secton on "weightx,weighty" states:

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container.

like image 30
camickr Avatar answered Nov 15 '22 16:11

camickr