tags:

views:

4123

answers:

4

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?

+4  A: 

Use JComponent.scrollRectToVisible()

If you need more info, here's an article

ykaganovich
A: 

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.

Vincent Ramdhanie
This didn't work for me - the ScrollPane jumps to the top then immediately drops down to the bottom again.
jwoolard
+11  A: 

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

Craig
You are right, the problem was that the caret was at the end of the text component. It also works after calling 'setText(...)' on the text editor. (tested with a JEditorPane instance as text panel inside the JScrollPane).
Guillaume Alvarez
A: 

Just in case you are not using a text component take a look at the thread posted here.... http://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);
   }
});
Eric W