【发布时间】:2017-05-09 13:29:40
【问题描述】:
我有一个cardlayout JPanel,里面是一个JScrollPane,里面是一个springlayout JPanel。 springlayout JPanel 是与 JPanel 从上到下动态添加的,但是当 JButtons 超出 JPanel 时,JScrollPane 不会容纳额外的内容。此外,尽管添加了内容,但显然 springlayout JPanel 的高度仍然为 0。将 resizable 属性设置为 true 也无济于事。
这是一个代码片段。我省略了卡片布局 JPanel 和代码切换卡片。
SpringLayout mainlayout = new SpringLayout();
JPanel maincard = new JPanel(mainlayout); // springlayout JPanel
for (int i = 0; i < info.size(); i++) {
GridLayout entryLayout = new GridLayout(1, 1);
JPanel entry = new JPanel(entryLayout);
entry.setSize(800, 30);
JButton name = new JButton();
name.setSize(250, 30);
name.setText(info.get(i).name);
entry.add(name);
mainlayout.putConstraint(SpringLayout.NORTH, entry,
i * 100 + 5,
SpringLayout.NORTH, maincard); // moves JPanel lower and lower
maincard.add(entry);
}
maincard.setSize(width, 30 * (info.size() + 1));
maincard.revalidate();
JScrollPane scroll = new JScrollPane(maincard);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setSize(200, 200); // this and setPreferredSize don't affect
cardpanel.add(scroll, cardName);
cardpanel.setSize(20, 200); // no effect
【问题讨论】:
-
apparently the springlayout JPanel's height remains 0- SpringLayout 是使用起来比较复杂的布局管理器之一,因为它需要所有的约束。我的建议是使用另一个布局管理器。或者,如果您真的想使用 SpringLayout,那么您需要阅读 How to Use SpringLayout 上的 Swing 教程中的部分以获取更多信息和工作示例。本教程还包含有关其他标准布局管理器的部分。 -
是的,我忘了提到我也尝试过其他布局。预期的输出应该类似于联系人列表,条目是 JPanel。我试过 GridLayout,但我无法控制条目的大小。对于 Box/BoxLayout,条目永远不会超出容器(网格布局也是如此)。 GridBagLayout 也有同样的问题。边框是不可能的(我不需要它来覆盖),并且流仅用于水平包装。
-
GridLayout 不起作用,因为组件的大小适合可用空间。 BoxLayout 或 GridBagLayout 可用于垂直添加组件。
标签: java swing jscrollpane cardlayout springlayout