Tazmanian Tad
Tazmanian Tad

Reputation: 313

Java Swing JPanel that doesn't stretch the width

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"

Upvotes: 1

Views: 346

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

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...

Upvotes: 4

Andrew Thompson
Andrew Thompson

Reputation: 168815

..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)

Upvotes: 4

Related Questions