Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

swing

People also ask

What is the difference between JScrollPane and scrollbar?

What are the differences between a JScrollBar and a JScrollPane in Java? A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling.

Is JScrollPane vertical scrollbar child field?

It is scrollpane's vertical scrollbar child. It is the display policy for the vertical scrollbar.


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.


Use JComponent.scrollRectToVisible()

If you need more info, here's an article