JScrollpane需要缩小其宽度

Mik*_*ike 11 java swing jscrollpane miglayout

我有一个JScrollpane,有一个JPanel在里面(与面板包含一些JLabelS).

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

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

she*_*non 14

可能最好的方法是使包含的组件始终与视口的宽度相同.为此,需要实现第一个包含的组件(子组件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;
    }
}
Run Code Online (Sandbox Code Playgroud)