简体   繁体   中英

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"

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM