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

pat*_*rit 5 java swing scroll jpanel jscrollpane

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

事情就加入到(或从中删除)的JPanel,当它超越了面板的底部,我想根据需要JScrollPane的向下自动滚动至底部或向上滚动,如果某些组件去远离面板.

我该怎么办?我猜我需要某种监听器,只要JPanel高度发生变化就会调用它?还是有一些简单的东西JScrollPanel.setAutoScroll(true)

小智 12

scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
        public void adjustmentValueChanged(AdjustmentEvent e) {  
            e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
        }
    });
Run Code Online (Sandbox Code Playgroud)

这将是最好的.从JScrollPane和JList自动滚动找到

  • 唯一的问题是您无法手动调整滚动条。 (2认同)

cam*_*ckr 6

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

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

JScrollBar sb = scrollPane.getVerticalScrollBar();
sb.setValue( sb.getMaximum() );
Run Code Online (Sandbox Code Playgroud)


Mat*_*aun 5

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

/**
 * 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
}
Run Code Online (Sandbox Code Playgroud)