1

Okay so I have a JPanel that is going to have two JLabels inside it, I can't seem to figure out a Layout or a way to make it so both the labels are aligned to the left and only take up the space needed for the content, most layouts I try only show one of the objects or show both space out evenly across the entire width, any help would be appreciated!

I've tried setting a max and preferred size on the panel with no luck =/ Both labels are on the same "row"

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Tazmanian Tad
  • 193
  • 1
  • 2
  • 12
  • You could add another panel to your JPanel with yet another layout. (Composite design pattern basically). – Dylan Meeus Nov 07 '14 at 02:57
  • 1
    `GridBagLayout` can do it...Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This will result in less confusion and better responses. Also have a look at [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Nov 07 '14 at 02:57

2 Answers2

4

..so both the labels are aligned to the left

Put it in a panel with layout:

new FlowLayout(FlowLayout.LEFT) 

Or (localized)

new FlowLayout(FlowLayout.LEADING)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • I could not get grid bag layout to display the second component in the panel so I gave this a try and it worked perfectly! – Tazmanian Tad Nov 07 '14 at 15:24
4

You could use a GridBagLayout, for example...

Squished

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
add(shrished, gbc);
gbc.gridx++;
gbc.weightx = 1;
add(shrishing, gbc);

"Wow", you say, "that looks complicated, why would I want to do that when other methods look easier"...good question, you could also do this...

Going north

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(shrished, gbc);
gbc.gridx++;
gbc.weightx = 1;
gbc.weighty = 1;
add(shrishing, gbc);

or this...

Going south

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.SOUTHWEST;
add(shrished, gbc);
gbc.gridx++;
gbc.weightx = 1;
gbc.weighty = 1;
add(shrishing, gbc);

With flexibility comes complexity, but it really comes down to exactly what you want to achieve...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366