【问题标题】:Java Swing: SpringLayout within BorderLayoutJava Swing:BorderLayout 中的 SpringLayout
【发布时间】:2014-12-28 05:01:24
【问题描述】:

我的 GridLayout 出现问题,其中 JTextField 加宽以适应比初始大小更长的条目。另一个有这个问题的海报被告知 SpringLayout 是最简单的解决方案,所以这就是我正在尝试的。但是,我无法让这个面板显示。

我有顶部、底部、左侧和右侧面板,每个面板都有不同的布局,这些面板设置在顶级面板(此框架中唯一的一个)中。我正在尝试的这个 SpringLayout 是在右侧面板中(添加到顶部面板作为 topPanel.add(springPanel, BorderLayout.EAST - 当这个面板是 GridLayout 时我就是这样做的)。下面的代码是模仿的SpringLayout Oracle 教程。抱歉,我是这个布局的新手,我只使用它来为 JTextFields 使用固定宽度。

JPanel testPanel = new JPanel();
SpringLayout layout = new SpringLayout();
testPanel.setLayout(layout);
JLabel label = new JLabel("First field: ");
JTextField field = new JTextField("enter text");

testPanel.add(label);
testPanel.add(field);

layout.putConstraint(SpringLayout.WEST, label, 5, SpringLayout.WEST, testPanel);
layout.putConstraint(SpringLayout.NORTH, label, 5, SpringLayout.NORTH, testPanel);
layout.putConstraint(SpringLayout.WEST, field, 5, SpringLayout.EAST, label);
layout.putConstraint(SpringLayout.NORTH, field, 5, SpringLayout.NORTH, testPanel);

...

topPanel.add(testPanel, BorderLayout.EAST);

任何指导将不胜感激。谢谢。

编辑:添加 cols 参数似乎不起作用,但我会继续尝试。 GridBagLayout 也存在同样的问题。切换到下一个字段不会重新调整前一个字段的大小,但是在框架中其他地方的这些字段之外单击会导致它扩展其包含文本的长度,这是我需要避免的。而且我没有足够的代表点来发布我正在做的事情的图片

EDIT2:添加 cols 工作 - 我在某个时候尝试过。不完全确定它是如何工作的,但是任何值(1、10、15 测试)似乎都可以固定长度,因此离开该面板的焦点不再导致大小变化。谢谢!

【问题讨论】:

  • SpringLayout 手动编码绝非简单。
  • JTextField field = new JTextField("enter text"); 应该类似于JTextField field = new JTextField("enter text", cols); 其中cols 是要显示的列数。
  • 1) 为了尽快获得更好的帮助,请发布MCVE(最小完整可验证示例)或SSCCE(简短、自包含、正确示例)。 2) 提供 ASCII 艺术,或简单的图形,GUI 的布局。
  • am only using it to use fixed widths for JTextFields. - GridBagLayout 应该尊重文本字段的首选大小。或者,您可以使用 FlowLayout 将文本字段添加到 JPanel,而不是将面板添加到 GUI。

标签: java swing layout-manager border-layout springlayout


【解决方案1】:

@Andrew Thompson 的回答有效 - 使用 col arg 指定列数(任何数字似乎都可以)。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多