仅在必要时在FlowLayout中显示ScrollBars

我会改写我的问题:**

如果有足够的空间通过变形来显示所有项目,如何防止在FlowLayout中启用Java ScrollBar。

例 **

这是我想要实现的截图:

请注意,在不需要时禁用滚动条。 在此处输入图像描述

当您调整窗口大小时,如果某些项目在视图平面外,则应显示滚动条 在此处输入图像描述

PS我知道称为文档和Web的东西。

您更新的屏幕截图表明您可能正在寻找Wrap Layout 。

默认滚动条策略是根据需要 ,但我记得必须考虑FlowLayout差距才能获得最初的偶数。 如果您将此示例拉出,您将看到水平滚动条消失。

更新:它并没有真正解决您的问题,但它显示了我如何实现Scrollable 。 我想摆脱setPreferredSize() ,即使是’图像只是一个占位符。 Wrap Layout文章讨论了为什么FlowLayout工作方式。

 import javax.swing.*; import java.awt.*; import java.util.Random; public class ImageScrollTest extends JPanel implements Scrollable { private static final int N = 8; private static final int W = 120; private static final int H = 100; private final FlowLayout layout = new FlowLayout(); private final int hGap = layout.getHgap(); private final int vGap = layout.getVgap(); private final Dimension size; // Show n of N images in a Scrollable FlowLayout public ImageScrollTest(int n) { setLayout(layout); for (int i = 0; i < N; i++) { this.add(new ImagePanel()); } size = new Dimension(n * W + (n + 1) * hGap, H + 2 * vGap); } @Override public Dimension getPreferredScrollableViewportSize() { return size; } @Override public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction) { return getIncrement(orientation); } @Override public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction) { return getIncrement(orientation); } private int getIncrement(int orientation) { if (orientation == JScrollBar.HORIZONTAL) { return W + hGap; } else { return H + vGap; } } @Override public boolean getScrollableTracksViewportWidth() { return false; } @Override public boolean getScrollableTracksViewportHeight() { return false; } private static class ImagePanel extends JPanel { private static final Random rnd = new Random(); private Color color = new Color(rnd.nextInt()); public ImagePanel() { this.setBackground(color); this.setBorder(BorderFactory.createLineBorder(Color.blue)); } @Override public Dimension getPreferredSize() { return new Dimension(W, H); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ImageScrollTest ist = new ImageScrollTest(N / 2); JScrollPane sp = new JScrollPane(ist); sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER); f.add(sp); f.pack(); f.setVisible(true); } } 

当您希望滚动条可以显示时(在水平和垂直方向都可能),您可以指定给scrollPane:

 myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 

还有: HORIZONTAL_SCROLLBAR_ALWAYSHORIZONTAL_SCROLLBAR_NEVER如果你很快就需要它。

编辑:有关更多信息,以及我的答案: http : //docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html