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

时间:2019-05-14 09:46:45

标签: java jscrollpane

嘿,我是新来的

我希望动态内容与父窗口一样宽(并随其宽度自动调整大小),但能够在需要时向下滚动(如果内容超出可用空间)。

我正在向Jpanel添加和删除JinternalFrameJScrollPanel之类的多种内容。

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

我尝试过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)更糟或相同

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

1 个答案:

答案 0 :(得分:0)

前段时间我遇到了类似的问题,并且能够使用自定义的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()返回true

相关问题