动态添加内容时将 Jscrollpanes 宽度限制为 Parents 宽度

Limit Jscrollpanes width to Parents width when dynamically adding content

嘿,我是新手

我希望动态内容与父内容一样宽 window(并根据其宽度自动调整大小)但可以在需要时向下滚动(如果内容超出可用范围 space)。

我正在向 JScrollPanel 添加和删除多个内容,例如 JpanelJinternalFrame

我试过的大多数东西,无论是自定义 类 还是布局管理器,都只是隐藏了滚动条(但没有阻止内容永远在水平方向上添加) 或者只是缩小了内容。

我试过了 https://tips4java.wordpress.com/2009/12/20/scrollable-panel/ 但它只会拉伸或收缩

public class MainView extends JFrame {

    private ScrollablePanel contentPane;
    private JScrollPane scrollPane;
...

在构造函数中:

...
contentPane = new ScrollablePanel(new BorderLayout());
        contentPane.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.NONE);
    contentPane.setScrollableHeight(ScrollablePanel.ScrollableSizeHint.NONE);
        contentPane.setBorder(new EmptyBorder(1, 1, 1, 1));
        scrollPane = new JScrollPane(contentPane);
        setContentPane(scrollPane);

不同的 Sizehints 或布局,如默认 Flowlayout 要么更差,要么相同

垂直滚动按预期工作但不限制水平方向的内容(而且我似乎不允许添加屏幕截图) 我不需要这个类,如果你认为它可以用其他方式实现

前段时间我遇到了类似的问题,用自定义的JPanel解决了:

/**
 * A panel that can be used in a JScrollPane which always adapts to the
 * width of the JScrollPane (so only vertical scrolling will happen).
 */
public class ParentWidthPanel extends JPanel implements Scrollable {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }

    @Override
    public int getScrollableUnitIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
        return 5;
    }

    @Override
    public int getScrollableBlockIncrement(final Rectangle visibleRect, final int orientation, final int direction) {
        return 15;
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
    if (getParent() instanceof JViewport) {
       return ((getParent()).getHeight() > getPreferredSize().height);
    }
    return false;
    }

}

要点是方法 getScrollableTracksViewportWidth() 到 return true