没有拉伸宽度的Java Swing JPanel

时间:2014-11-07 02:55:16

标签: java swing layout-manager

好的,所以我有一个JPanel,里面会有两个JLabel,我似乎无法弄清楚布局或制作它的方法,所以两个标签都对齐到左侧,只占用内容所需的空间,我尝试的大多数布局只显示其中一个对象或在整个宽度上均匀显示两个空间,任何帮助将不胜感激!

我已尝试在面板上设置最大和首选尺寸但没有运气= /两个标签位于同一行"行"

2 个答案:

答案 0 :(得分:4)

  

..因此两个标签都与左侧对齐

将它放在带布局的面板中:

new FlowLayout(FlowLayout.LEFT) 

或(本地化)

new FlowLayout(FlowLayout.LEADING)

答案 1 :(得分:4)

您可以使用GridBagLayout,例如......

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",你说,"看起来很复杂,为什么我想在其他方法看起来更容易时做到这一点" ...好问题,你也可以这样做。 ..

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

或者这......

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

灵活性带来了复杂性,但它确实归结为您想要实现的目标......