java BorderLayout:嵌套的中心面板会增长,但不会调整外部面板的大小
我有一个主JPanel,它实现了可滚动并使用了BorderLayout。它包含一个北方的只读JEditorPane,一个中间的JPanel,带有一个FlowLayout,可以动态添加JButton,还有一个南方的JLabel,所有这些都是按顺序添加的。当许多JButtons被添加到中心JPanel时,按钮会缠绕到下一行:问题是,中心JPanel占用的超过一行的垂直空间只是与南部JLabel重叠,不会导致整个JPanel动态增长或显示垂直滚动条。另一方面,当足够多的文本被添加到NORTH JEditorPane中,使其换行到下一行时,它会按照我的预期进行操作,并向下推动中间的JPanel,显示垂直滚动条
以下是主要的JPanel可滚动实现:
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);
}
我做错了什么?我怎样才能让中心的杰帕内尔把南杰帕内尔往下推,使整个主要的杰帕内尔生长起来
# 1 楼答案
问题是当按钮被包装到下一行时,FlowLayout不会重新计算首选大小
你应该能够使用WrapLayout
WrapLayout
扩展FlowLayout
并在组件换行时设置适当的首选大小