11

我有一个内部JScrollpane有一个JPanel(并且面板包含一些JLabels)。

我想调整滚动窗格的大小以实际更改其大小(可能低于内部组件的首选大小),而不仅仅是视口的大小。

目标是当用户将滚动窗格缩小得太小时,内部面板优雅地消失(在我的 miglayout 中使用特定的缩小优先级等)。

4

1 回答 1

16

可能最好的方法是让包含的组件始终与视口的宽度相同。为此,第一个包含的组件(作为 的子组件JViewPort、传递到JScrollPane构造函数或设置为 的组件viewportView)需要实现javax.swing.Scrollable. 关键方法是getScrollableTracksViewportWidth,应该返回true

这是一个快速而肮脏的可滚动 JPanel :

public class ScrollablePanel extends JPanel implements Scrollable {
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }

    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
       return 10;
    }

    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return ((orientation == SwingConstants.VERTICAL) ? visibleRect.height : visibleRect.width) - 10;
    }

    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
}
于 2010-05-11T21:53:55.913 回答