How to Set the Scrollbar in Java
In a windowed program, a scroll window contains a scrollbar and a scroll pane. A scrollbar is the property of the scroll pane, which acts as a viewport onto a surface too large for the window to contain. The user can change the scrollbar's position by clicking its arrow buttons or by activating code you've written to change the scrollbar "manually." In Java, the code you need depends on whether you're using the Java AWT toolkit or Java Swing. If you're using the Swing toolkit, you'll need to wrap your code in a special thread to change the scrollbar's properties.
Instructions
-
With AWT
-
1
Grab the reference to your scroll pane, such as "ScrollPane myPane."
-
2
Change the scrollbar's position by calling "pane.setScrollbarPosition(int, int)", where the first parameter is the scrollbar's "X" position and the second is the scrollbar's "Y" position.
-
-
3
Set whether or not you can control the scrollbar with the mouse wheel by calling "setWheelScrollingEnabled(boolean)", where "true" enables scrolling via mouse wheel, and "false" disables it.
With Swing
-
4
Create a new SwingWorker thread. A SwingWorker thread runs simultaneously with the main GUI display thread. Any code that you place here will execute after the GUI makes its changes, which is important if you're setting your scrollbar with a command issued through the GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {}
}); -
5
Grab the reference to your scrollbar, which, if you're starting from a JScrollPane, is as follows:
myPane.getHorizontalScrollbar();
or
myPane.getVerticalScrollbar();
These methods return a JScrollBar object representing the horizontal or vertical scrollbar.
-
6
Use the method JScrollBar.setValue(int) to set the scrollbar's position.
-
7
Use the method JScrollBar.setUI(ScrollBarUI) to set the scrollbar's look and feel.
-
8
Use the method JScrollBar.setUnitIncrement(int) to define by how much the scrollbar changes when the user clicks the up or down arrow.
-
1
Tips & Warnings
In Swing, a scrollbar's true position is set by a BoundedRangeModel object with four parameters: minimum, maximum, value and extent. "Minimum" and "maximum" define the scrollbar's lower and upper boundaries, respectively. "Value" is the current start point of the scrollbar, or the current top of the scrollbar's knob. "Extent" defines how low the knob extends. To scroll to the top of the screen, set the value to the minimum value using JScrollBar.getMinimum().
If you don't invoke GUI changing-code in its own SwingWorker thread when using Swing, the GUI may execute its own code after yours, effectively nullifying your changes.
References
- Photo Credit Jupiterimages/Comstock/Getty Images