Creating Scrollbar Using JScrollBar Class

In this tutorial, you will learn how to use JScrollBar class to create scrollbars in Java Swing application.

A scrollbar consists of a rectangular tab called slider or thumb located between two arrow buttons. Two arrow buttons control the position of the slider by increasing or decreasing a number of units, one unit by default. The area between the slider and the arrow buttons is known as paging area. If user clicks on the paging area, the slider will move one block, normally 10 units. The slider’s position of scrollbar can be changed by:

  • Dragging the slider up and down or left and right.
  • Pushing on either of two arrow buttons.
  • Clicking the paging area.

In addition, user can use scroll wheel on computer mouse to control the scrollbar if it is available.

To create a scrollbar in swing, you use JScrollBar class. You can create either vertical or horizontal scrollbar.

Here are the JScrollBar’s constructors.

JScrollBar()Creates a vertical scrollbar.
JScrollBar(int orientation)Creates a scrollbar with a given orientation.
JScrollBar(int orientation, int value, int extent, int min, int max)Creates a scrollbar with a given orientation and initialize the following scrollbar’s properties: value, extent, minimum, and maximum.

Example of using JScrollBar

In this example, we will create a vertical and horizontal scrollbars. The position of the slider will be updated whenever the position of the slider changed.

Here is the screenshot of the demo application:

Java Swing - Scrollbar

  • Was this tutorial helpful ?
  • YesNo