You are here:   HomeJava ProgrammingSwingGridBagLayout in Java Swing Example
by Dinesh Thakur Category: Swing

Scroll bars are horizontally or vertically oriented bars which allow the user to select items between a specified minimum and maximum values. Each end of the scroll bar has an arrow which can be clicked to change the current value of the scroll bar. The slider box indicates the current value of the scroll bar which can be dragged by the user to a new position. Scrollbar is an object of ScrollBar class.

Some of the constructors defined by ScrollBar class are as follows.

JScrollBar() //first

JScrollBar(int orientation) //second

JScrollBar(int orientation, int initial_value, int visible units, int min, int max) //third

The first constructor creates a vertical scroll bar. The second constructor creates a scrollbar in which orientation specifies the orientation of the scroll bar which can take one of the following values JScrollBar.HORIZONTAL or JScrollBar.VERTICAL. The third constructor creates a scroll bar in which orientation specifies the orientation of the scroll bar, initial_value represents the initial value of the scrollbar, visible_units represents the number of visible items of a scroll bar at a time and min and max represents the minimum and maximum values for the scroll bar.

Consider the Example. Here, two scrollbars (one horizontal and one vertical) are added

Example An applet to demonstrate the use of Scrollbar class

import javax.swing.*;

public class ScrollBarExample extends JApplet

{

   ScrollBarExample()

   {

       JFrame jf;

       jf=new JFrame("ScrollBar");

       JPanel jp=new JPanel();

       JLabel j11=new JLabel("Scrollbar:");

       JScrollBar jsv=new JScrollBar();

       JScrollBar jsh=new JScrollBar(JScrollBar.HORIZONTAL);

       jp.add(j11);

       jp.add(jsv);

       jp.add (jsh);

       jf.add (jp);

       jf.setDefaultCloseOperation(jf.EXIT_ON_CLOSE);

       jf.setSize(300,200);

       jf.setVisible(true);

    }

       public static void main(String[] args)

        {

            ScrollBarExample japp= new ScrollBarExample();

        }

}

The output of the above code is Figure

                 Scrollbar Example

What's New and Popular