[英]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! 好的,我有一个JPanel,里面将有两个JLabel,我似乎无法弄清楚Layout或制作方法,因此两个标签都向左对齐,只占用了所需的空间。内容,我尝试的大多数布局仅显示其中一个对象,或者在整个宽度上均匀地显示两个空间,对您有所帮助!
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
..so两个标签都向左对齐
Put it in a panel with layout: 将其放在具有布局的面板中:
new FlowLayout(FlowLayout.LEFT)
Or (localized) 或(本地化)
new FlowLayout(FlowLayout.LEADING)
You could use a GridBagLayout
, for example... 您可以使用
GridBagLayout
,例如...
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... 灵活性带来了复杂性,但实际上确实要达到您想要实现的目标...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.