JSlider Example Java Swing

JSlider Example Java Swing

JSliders enable the user to select from a range of integer values. Class JSlider inherits form JComponent. The following program creates a horizontal JSlider with tick marks and the thumb that allows the user to select a value.

JSliders can be customized so that they can display major tick marks, minor tick marks and labels for the tick marks. They also support snap-to-ticks where positioning the thumb between two tick marks causes the thumb to snap to the closest tick mark.

JSliders have either a horizontal orientation or a vertical orientation. For a horizontal JSlider, the minimum value is at the extreme left and the maximum value is at the extreme right of the JSlider. For a vertical JSlider, the minimum value is at the extreme bottom and the maximum value is at the extreme top of the JSlider. The relative position of the thumb indicates the current value of the JSlider.

In the following program, slider is used to change its value when the slider thumb is dragged. The slider is set to a minimum value 0 and to a maximum value 255. These values are used as the green component in making a color object. This color object is applied as a background color to the canvas. Canvas is a component on which we can do a free-hand writing or painting as in paint of accessories in Windows. Whenever, the slider is moved, the background color of the canvas is changed.

We used a swing listener, ChangeListener to handle the slider events. It defines one abstract method stateChanged(ChangeEvent e) which we must override in our program.

Following program changes the background of the canvas when ever slider is clicked or dragged.


js = new JSlider(SwingConstants.HORIZONTAL, 0, 255, 15 );

The above statement creates a horizontal slider. The slider moves in between a minimum value of 0 and a maximum value 255. Every click on the slider, moves the thumb of the slider by 15.

AWT scroll bar program is available at Scrollbar With Insets.

Leave a Reply

Your email address will not be published. Required fields are marked *