Search code examples
javaswinguser-interfacelayout-managergridbaglayout

Java GridBagLayout components positioning


I'm trying to make a simple layout where the labels are next to the buttons and close. Here is the order I am adding them:

add(label_1, cons);

cons.gridx = 1;
add(textArea,cons);

cons.gridx = 0;
cons.gridy = 2;
add(button_1,cons);

cons.gridx= 0;
cons.gridy = 4;
add(button_2,cons);

cons.gridx=0;
cons.gridy=6;
add(button_3,cons);

cons.gridx = 1;
cons.gridy = 2;
add(label_2, cons);       

cons.gridy=4;
add(label_3,cons);

cons.gridy=6;
add(label_4,cons);

Which looks like this:

enter image description here

I just need the labels positioned closer to the buttons, but it seems the closest x value I can give them is 1, it seems relatively positioned - is there a way I could absolutely position them?


Solution

  • You have several options available to you, depending on how you want this to look like, all explained in the already posted tutorial.

    1. Set the fill field of the constraints to HORIZONTAL and alignment of the labels to WEST (Or LINE_START, whichever you're used to), along with a positive weightx. This will make both the labels and buttons occupy all available horizontal space, and their alignment will mean the text will be on the left edge.
    2. Use the anchor field. This controls where a smaller component would be located in it's cell - you likely want a right or central alignment for the buttons, and left for the labels.
    3. If you want the labels to be close to the buttons without anything changing size, then a grid will not serve you very well, since the "Enter a sentence" field is too long. You may want to have 2 different panels for the top and bottom (BorderLayout much?), or a more intelligent layout manager