JScrollpane需要缩小其宽度

我有一个JScrollpaneJPanelJScrollpane (面板包含一些JLabel )。

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

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

可能最好的方法是使包含的组件始终与视口的宽度相同。 为此,第一个包含的组件( JViewPort的子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; } }