How to Scroll to the Top of a Scrollpane in Java

How to Scroll to the Top of a Scrollpane in Java thumbnail
A scrollpane lets you run a program in windowed mode.

In Java, a scrollpane creates a scrollable viewport with which you can view a text area or picture too large for the screen. The code needed to scroll to the top of a Java scrollpane depends on which type of scrollpane you are using. The class "ScrollPane" in the Java AWT uses "setScrollPosition" to record the position of the viewport, while "JScrollPane" in the Swing Toolkit uses "JScrollBar.setValue()." You might not see any changes unless you force the method to run after the Swing components update, which you can do by using the Swing method "invokeLater."

Instructions

  1. Using ScrollPane

    • 1

      Find the reference to your scrollpane, such as "ScrollPane pane."

    • 2

      Record the value of your scroll pane's horizontal component, if any:

      int xPos = pane.getScrollPosition().x;

    • 3

      Set the vertical component of your scrollpane's position to "0" via the "setScrollPosition()" method:

      pane.setScrollPostion(xPos, 0);

    Using JScrollPane

    • 4

      Create a new thread to invoke later:

      javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
      //Code for Steps 2 through 4 goes here
      }
      });

    • 5

      Retrieve the reference to your scrollPane, such as "JScrollPane spane." Access the vertical scrollbar with "getVerticalScrollBar()."

    • 6

      Set the scroll bar to its minimum value, such as "vscrollbar.setValue(vscrollbar.getMinimum)."

Related Searches:

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images

Comments

Related Ads

Featured