【问题标题】:Java Swing JPanel that doesn't stretch the width不拉伸宽度的 Java Swing JPanel
【发布时间】:2014-11-07 12:20:40
【问题描述】:

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

我尝试在面板上设置最大和首选尺寸,但没有成功 =/ 两个标签都在同一“行”上

【问题讨论】:

标签: java swing layout-manager


【解决方案1】:

..所以两个标签都向左对齐

把它放在一个有布局的面板中:

new FlowLayout(FlowLayout.LEFT) 

或(本地化)

new FlowLayout(FlowLayout.LEADING)

【讨论】:

  • 我无法让网格包布局在面板中显示第二个组件,所以我试了一下,效果很好!
【解决方案2】:

您可以使用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);

“哇”,你说,“这看起来很复杂,当其他方法看起来更简单时,我为什么要这样做”......好问题,你也可以这样做......

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

或者这个……

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 2014-01-22
    • 1970-01-01
    • 2016-04-19
    相关资源
    最近更新 更多