BorderLayout: Nested CENTER Panel Grows But does Not Resize Outer Panel
I have a main JPanel which implements Scrollable and uses a BorderLayout. It contains one NORTH readonly JEditorPane, one CENTER JPanel with a FlowLayout whereby JButtons are added dynamically, and one SOUTH JLabel, all added in that order. When many JButtons are added to the CENTER JPanel, the buttons wrap onto the next rows: the problem is that the vertical space exceeding one row taken up by the CENTER JPanel just overlaps with the SOUTH JLabel and does not cause the entire JPanel to grow dynamically or show the vertical scrollbar. On the other hand, when enough text is added to NORTH JEditorPane so that it wraps to the next rows, it does behavior as I'd expect and push the CENTER JPanel down and show the vertical scrollbars.
Here main JPanel Scrollable implementation:
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) getPar开发者_StackOverflowent();
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);
}
What am I doing wrong? How can I make the CENTER JPanel push the SOUTH JLabel down to grow the entire main JPanel?
The problem is that the FlowLayout does not recalculate the preferred size when buttons are wrapped to the next row.
You should be able to use the WrapLayout.
WrapLayout
extends FlowLayout
and sets the proper preferred size when components wrap to a new row.
精彩评论