我有一个主 JPanel,它实现了 Scrollable 并使用了 BorderLayout。它包含一个 NORTH 只读 JEditorPane、一个带有 FlowLayout 的 CENTER JPanel,其中 JButton 是动态添加的,以及一个 SOUTH JLabel,全部按该顺序添加。当向 CENTER JPanel 添加许多 JButton 时,按钮会包裹到下一行:问题是 CENTER JPanel 占用的超过一行的垂直空间只是与 SOUTH JLabel 重叠,并不会导致整个 JPanel 动态增长或显示垂直滚动条。另一方面,当向 NORTH JEditorPane 添加足够的文本以便它换行到下一行时,它会按照我的预期进行行为,并将 CENTER JPanel 向下推并显示垂直滚动条。
这里是 JPanel Scrollable 的主要实现:
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
return Math.max(visibleRect.height * 9 / 10, 1);
}
public boolean getScrollableTracksViewportHeight() {
if (getParent() instanceof JViewport) {
JViewport viewport = (JViewport) getParent();
return getPreferredSize().height < viewport.getHeight();
}
return false;
}
public boolean getScrollableTracksViewportWidth() {
return true;
}
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
return Math.max(visibleRect.height / 10, 1);
}
我做错了什么?如何使 CENTER JPanel 将 SOUTH JLabel 向下推以扩大整个主 JPanel?
最佳答案
问题在于,当按钮换行到下一行时,FlowLayout 不会重新计算首选大小。
您应该能够使用 WrapLayout 。
WrapLayout
扩展 FlowLayout
并在组件换行到新行时设置适当的首选大小。
关于java - 边框布局 : Nested CENTER Panel Grows But does Not Resize Outer Panel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3575745/