public void createSpringLayout(SpringLayout spring, JLabel label, JScrollPane scrollPane, JPanel buttonPanel) {
spring.putConstraint(SpringLayout.NORTH, label, 10, SpringLayout.NORTH, this);
spring.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST, this);
spring.putConstraint(SpringLayout.NORTH, scrollPane, 10, SpringLayout.SOUTH, label);
spring.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, label);
spring.putConstraint(SpringLayout.EAST, scrollPane, -10, SpringLayout.EAST, this);
spring.putConstraint(SpringLayout.NORTH, buttonPanel, Spring.constant(10, 30, 30), SpringLayout.SOUTH, scrollPane);
spring.putConstraint(SpringLayout.SOUTH, buttonPanel, -10, SpringLayout.SOUTH, this);
spring.putConstraint(SpringLayout.WEST, buttonPanel, 0, SpringLayout.WEST, label);
}
两个带有所有内容的 Jpanel 使用相同的父类(super class)以获得更好的外观。 但是,正如您所看到的,如果滚动 Pane 的内容太宽,则滚动 Pane 只会使用底部的额外空间来创建水平滚动条。 即使我告诉 Springlayout 滚动 Pane 和按钮面板之间的 Spring 可以在 10 到 30 之间。
我认为首先调用 SpringLayoutManager 来布局其组件,然后 ScrollPane 出现并注意到其显示的组件不适合视口(viewport)并创建一个滚动条,而 SpringLayoutManager 不知道这一点。
我找不到任何解决方案可以预先告诉 ScrollPane 计算其所需的大小,或者让它不使用比一开始就多的空间。
最佳答案
不要将负数传递给 putConstraint
。
来自the documentation of putConstraint :
Links edge e1 of component c1 to edge e2 of component c2, with a fixed distance between the edges.
pad
值不是绝对像素偏移,它是组件与链接边缘之间的填充量(距离)。它应该始终是积极的。
同一个 javadoc 还将 pad
参数描述为:
pad
- the fixed distance between dependent and anchor
SpringLayout 很复杂,这意味着使用它很容易出错。您可以使用 BorderLayout 轻松完成相同的布局:
setLayout(new BorderLayout());
add(label, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
this.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
关于java - JScrollBar 布局管理器和 SpringLayout 管理器不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75387016/