Java Swing - Using JScrollPane and Having it scroll back to top

JavaSwing

Java 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

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); 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobynView Question on Stackoverflow
Solution 1 - JavaCraigView Answer on Stackoverflow
Solution 2 - JavaEric WarrinerView Answer on Stackoverflow
Solution 3 - JavaPb600View Answer on Stackoverflow
Solution 4 - JavaaosphymaView Answer on Stackoverflow
Solution 5 - JavaykaganovichView Answer on Stackoverflow
Solution 6 - JavaVincent RamdhanieView Answer on Stackoverflow
Solution 7 - JavaRichard TView Answer on Stackoverflow