Reputation: 313
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
Reputation: 347184
You could use a GridBagLayout
, for example...
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...
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...
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
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