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

我有一个带有JScrollPane的简单JPanel(根据需要有垂直滚动条)。 事情被添加到JPanel中(或从中移除)当它超出面板底部时,我希望JScrollPane根据需要自动向下滚动到底部,或者如果某些组件离开面板则向上滚动。 我该怎么做? 我猜我需要某种监听器,只要JPanel高度发生变化就会被调用? 或者有一些像JScrollPanel.setutoScroll(true)这样简单的东西?

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

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

JScrollBar sb = scrollPane.getVerticalScrollBar(); sb.setValue( sb.getMaximum() ); 
 scrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { e.getAdjustable().setValue(e.getAdjustable().getMaximum()); } }); 

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

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

 /** * 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.equals(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 since otherwise the user would be unable to scroll afterwards verticalBar.removeAdjustmentListener(this); } }; verticalBar.addAdjustmentListener(scroller); } public enum ScrollDirection { UP, DOWN }