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, users can use the scroll wheel on a computer mouse to control the scrollbar if it is available.

To create a scrollbar in swing, you use JScrollBar class. You can create either a 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
package jscrollbardemo; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Main { public static void main(String[] args) { final JFrame frame = new JFrame("JScrollbar Demo"); final JLabel label = new JLabel( ); JScrollBar hbar=new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 500); JScrollBar vbar=new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 500); class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent e) { label.setText("Slider's position is " + e.getValue()); frame.repaint(); } } hbar.addAdjustmentListener(new MyAdjustmentListener( )); vbar.addAdjustmentListener(new MyAdjustmentListener( )); frame.setLayout(new BorderLayout( )); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,200); frame.getContentPane().add(label); frame.getContentPane().add(hbar, BorderLayout.SOUTH); frame.getContentPane().add(vbar, BorderLayout.EAST); frame.getContentPane().add(label, BorderLayout.CENTER); frame.setVisible(true); } }
Code language: PHP (php)