Java Swing - 使用 JScrollPane 并让它滚动回顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/291115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Swing - Using JScrollPane and Having it scroll back to top
提问by
I'm using JScrollPane to allow scrolling in a JFrame that has a text component that's serving as a text editor. What I want to do, after setting the text in this editor, is have it scroll back up to the top, so you can see what's at the beginning of the file.
我正在使用 JScrollPane 来允许在具有用作文本编辑器的文本组件的 JFrame 中滚动。在此编辑器中设置文本后,我想要做的是让它向上滚动到顶部,这样您就可以看到文件开头的内容。
Does anyone know how to do this?
有谁知道如何做到这一点?
回答by ykaganovich
Use JComponent.scrollRectToVisible()
使用JComponent.scrollRectToVisible()
If you need more info, here's an article
如果你需要更多信息,这里有一篇文章
回答by Vincent Ramdhanie
You can try this:
你可以试试这个:
scrollPane.getViewport().setViewPosition(new Point(0,0));
According to the JavaDocs setViewPosition() behaves like this:
根据 JavaDocs setViewPosition() 的行为如下:
Sets the view coordinates that appear in the upper left hand corner of the viewport, does nothing if there's no view.
设置出现在视口左上角的视图坐标,如果没有视图则不执行任何操作。
回答by Craig
Calling setCaretPosition(0)on your text component will cause it to scroll to the top.
在文本组件上调用setCaretPosition(0)将导致它滚动到顶部。
回答by Eric Warriner
Just in case you are not using a text component take a look at the thread posted here.... Setting Scroll Bar on a JScrollPane
以防万一您不使用文本组件,请查看此处发布的线程....在 JScrollPane 上设置滚动条
Their solution is to spin off a thread via invokeLater
他们的解决方案是通过 invokeLater 分拆一个线程
final JScrollPane scroll = new JScrollPane(text);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
scroll.getVerticalScrollBar().setValue(0);
}
});
回答by Pb600
This will make the work:
这将使工作:
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
回答by aosphyma
You can use the method setCaretPosition(0)
just after setText(String t)
of your text component.
您可以setCaretPosition(0)
在setText(String t)
文本组件之后使用该方法。
回答by Richard T
Here's how:
就是这样:
textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);