Java Swing-使用 JScrollPane 并让它滚动回顶部

我使用 JScrollPane 允许在一个具有文本组件的 JFrame 中进行滚动,该组件用作文本编辑器。在这个编辑器中设置文本之后,我想要做的是让它滚动回顶部,这样您就可以看到文件开头的内容。

有人知道怎么做吗?

74954 次浏览

You can try this:

 scrollPane.getViewport().setViewPosition(new Point(0,0));

According to the JavaDocs setViewPosition() behaves like this:

Sets the view coordinates that appear in the upper left hand corner of the viewport, does nothing if there's no view.

Calling setCaretPosition(0) on your text component will cause it to scroll to the top.

Just in case you are not using a text component take a look at the thread posted here.... Setting Scroll Bar on a JScrollPane

Their solution is to spin off a thread via invokeLater

final JScrollPane scroll = new JScrollPane(text);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
scroll.getVerticalScrollBar().setValue(0);
}
});

This will make the work:

DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);

You can use the method setCaretPosition(0) just after setText(String t) of your text component.

Here's how:

textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);