The class JScrollBar
represents the scroll bar in Swing. The scroll bar is used to determine the viewing area of the component in Swing. The scroll bar involves a knob that can be adjusted by the user and that shows the displayable contents of the component.
The scroll bar has the following properties that specify the position of the knob and the scroll bar track:
orientation
: This indicates a horizontal or a vertical Scrollbar.value
: This indicates the model’s current value. The upper limit on the model’s value is maximum - extent
and the lower limit is minimum
.extent
: This indicates the width of the knob of the scrollbar.minimum
: This indicates the minimum width of the track on which the scrollbar moves.maximum
: This indicates the maximum width of the track on which the scrollbar moves.All the properties above are bundled into a model.
JScrollBar
The different constructors of JScrollBar
that can be used while creating a JScrollBar
object are as follows:
JScrollBar()
This constructor is used to construct a JScrollBar
object with the following initial values:
JScrollBar(int orientation)
This constructor is used to construct a scroll bar with the given orientation. With orientation=0
, we get a horizontal scroll bar, and with orientation=1
, we get a vertical scroll bar.
JScrollBar(int orientation, int value, int extent, int min, int max)
This constructor is used to construct a JScrollBar
object with the given properties.
JScrollBar
classThe most commonly used methods of the JScrollBar
class are as follows:
The addAdjustmentListener(AdjustmentListener l)
method adds a listener to the specified JScrollBar
instance. The listener will be notified every time a change to the model of the scroll bar is detected.
The getModel()
method returns the model of the scroll bar.
The getMaximum()
method returns the maximum value (maximum - extent
) of the scrollbar.
The getMinimum()
method returns the minimum value of the scroll bar.
The getOrientation()
method returns the orientation of the scroll bar.
The getValue()
method returns the scrollbar’s value.
The setMaximum()
method is used to set the maximum value of the scrollbar.
The setMinimum()
method is used to set the minimum value of the scroll bar.
The setOrientation()
method is used to set the orientation of the scroll bar.
The setValue()
method is used to set the scrollbar’s value.
import javax.swing.*;import java.awt.*;class Main{public static void main(String[] args) {final JFrame frame = new JFrame("JScrollbar Demo");JScrollBar scrollBarH = new JScrollBar(JScrollBar.HORIZONTAL, 30, 20, 0, 500);JScrollBar scrollBarV = new JScrollBar(JScrollBar.VERTICAL, 30, 40, 0, 500);frame.setSize(300,200);frame.getContentPane().add(scrollBarH, BorderLayout.SOUTH);frame.getContentPane().add(scrollBarV, BorderLayout.EAST);frame.setVisible(true);}}
Following is the explanation of the given code:
JFrame
called frame
.scrollBarH
.scrollBarV
.scrollBarH
to the frame.scrollBarV
to the frame.true
.