tags:

views:

31

answers:

1

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) 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);
}

What am I doing wrong? How can I make the CENTER JPanel push the SOUTH JLabel down to grow the entire main JPanel?

+1  A: 

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.

camickr
Thanks, this has helped to grow the panel and trigger the vertical scrollbar. However, when I scroll down, the panel and its buttons hover over the content above the ScrollPane instead of disappearing behind its borders: http://www.screencast.com/t/MTUyOGRmY
Stephen Swensen
First try the code using a regular panel without your custom implementation of the Scrollable interface. If you still have a problem then post your SSCCE (http://sscce.org) that demonstrates the problem. We can't guess what your code is like from a picture.
camickr
OK, thanks. FYI - upon further investigation, it's only the buttons that are not disappearing, when I set the panel opaque to true, I can see that the panel itself is disappearing behind the bounds of the scroll pane. Same problem when I remove the custom Scrollable implementation.
Stephen Swensen
HAHAHA, I figured out the problem with the buttons was the code I am working from was using java.awt.Button instead of JButton! But your suggestion to use the WrapLayout was the solution to my original question, so, thank you!
Stephen Swensen