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

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

问题描述:

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

I have a simple JPanel with a JScrollPane (with vertical scrollbar as needed) on it.

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

Things get added to (or removed from) the JPanel and when it goes beyond the bottom of the panel, I want the JScrollPane to scroll down to the bottom automatically as needed or scroll up if some components go away from the panel.

我该怎么做?我想我需要某种侦听器,只要JPanel高度发生变化,该侦听器就会被调用?还是有像JScrollPanel.setAutoScroll(true)这样简单的东西?

How shall I do this? I am guessing I need some kind of listener which gets called whenever the JPanel height changes? Or is there something as simple as JScrollPanel.setAutoScroll(true)?

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

When you add/remove components for a panel you should invoke revalidate() on the panel to make sure the components are laid out properly.

然后,如果要滚动到底部,则应该可以使用:

Then, if you want to scroll to the bottom then you should be able to use:

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