Java Swing - Using JScrollPane and Having it scroll back to top
JavaSwingJava Problem Overview
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.
Does anyone know how to do this?
Java Solutions
Solution 1 - Java
Calling setCaretPosition(0) on your text component will cause it to scroll to the top.
Solution 2 - Java
Just in case you are not using a text component take a look at the thread posted here.... https://stackoverflow.com/questions/1166072/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);
}
});
Solution 3 - Java
This will make the work:
DefaultCaret caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
Solution 4 - Java
You can use the method setCaretPosition(0)
just after setText(String t)
of your text component.
Solution 5 - Java
Use JComponent.scrollRectToVisible()
If you need more info, here's an article
Solution 6 - Java
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.
Solution 7 - Java
Here's how:
textArea.setSelectionStart(0);
textArea.setSelectionEnd(0);