如何在Java Swing中自动滚动到底部

问题描述 投票:5回答:3

我有一个带有JScrollPane(根据需要有垂直滚动条)的简单JPanel。

事情被添加到JPanel(或从JPAnel中删除),当它超出面板底部时,我希望JScrollPane根据需要自动向下滚动到底部,或者如果某些组件离开面板则向上滚动。

我该怎么办?我猜我需要某种监听器,只要JPanel高度发生变化就会调用它?或者有什么像JScrollPanel.setAutoScroll(true)一样简单?

java swing scroll jpanel jscrollpane
3个回答
4
投票

为面板添加/删除组件时,应调用面板上的revalidate()以确保组件正确布局。

然后,如果你想滚动到底部,那么你应该可以使用:

JScrollBar sb = scrollPane.getVerticalScrollBar();
sb.setValue( sb.getMaximum() );

12
投票
scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
        public void adjustmentValueChanged(AdjustmentEvent e) {  
            e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
        }
    });

这将是最好的。来自JScrollPane and JList auto scroll


4
投票

这就是我自动向上或向下滚动的方式:

/**
 * Scrolls a {@code scrollPane} all the way up or down.
 *
 * @param scrollPane the scrollPane that we want to scroll up or down
 * @param direction  we scroll up if this is {@link ScrollDirection#UP},
 *                   or down if it's {@link ScrollDirection#DOWN}
 */
public static void scroll(JScrollPane scrollPane, ScrollDirection direction) {
    JScrollBar verticalBar = scrollPane.getVerticalScrollBar();
    // If we want to scroll to the top, set this value to the minimum,
    // else to the maximum
    int topOrBottom = direction == ScrollDirection.UP ?
                      verticalBar.getMinimum() :
                      verticalBar.getMaximum();

    AdjustmentListener scroller = new AdjustmentListener() {
        @Override
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Adjustable adjustable = e.getAdjustable();
            adjustable.setValue(topOrBottom);
            // We have to remove the listener, otherwise the
            // user would be unable to scroll afterwards
            verticalBar.removeAdjustmentListener(this);
        }
    };
    verticalBar.addAdjustmentListener(scroller);
}

public enum ScrollDirection {
    UP, DOWN
}
© www.soinside.com 2019 - 2024. All rights reserved.