0

I have been messing around with the GridBagLayout and am having a little bit of trouble. First I was trying to get the labels to start in the upper left which I accomplished with:

    JPanel right = new JPanel(new GridBagLayout());
    right.setPreferredSize(new Dimension(333,600));

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.NORTHWEST;

    JLabel testLabel = new JLabel();
    testLabel.setText("Test");
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.weightx = 1;
    right.add(testLabel, gbc);

Now I want to add another label directly under this one:

    JLabel test2Label = new JLabel();
    test2Label.setText("test2");
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.weighty = 1;
    gbc.weightx = 1;
    right.add(test2Label, gbc);

Instead of putting it directly under the first one it places it halfway down the panel. Its because of the weighty and weightx I think, but if I change these then it will not place the labels in the upper left. How can I make it work? Sorry if that is unclear English is not my best language so let me know if you need me to clarify. -Thanks

1 Answers1

0

If I understood you correctly, following code should be the answer. weightx and weighty decide how to distribute the free space in a component to its child components - the bigger value, the more space (read more here: Weightx and Weighty in Java GridBagLayout) but if you left all components with the value zero, they all will be centred.

So in your case, the best solution will be giving the whole left space to the second component.

GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;

JLabel testLabel = new JLabel();
testLabel.setText("Test");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 0;
gbc.weightx = 0;
right.add(testLabel, gbc);

JLabel test2Label = new JLabel();
test2Label.setText("test2");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weighty = 1;
gbc.weightx = 1;
right.add(test2Label, gbc);
Community
  • 1
  • 1
RetteMich
  • 125
  • 1
  • 9