The JSlider Class

The JSlider class represents a graphical slider. Like scrollbars, sliders can have either a horizontal or vertical orientation. With sliders, however, you can enhance their appearance with tick marks and labels.
Sliders represent a selection of one value from a bounded range. Scrollbars represent a range of values within a bounded range and are best used in things like the JScrollPane.
The JSlider class allows you to set the spacing of two types of tick marks: major and minor. Major tick marks are longer than minor tick marks and are generally used at wider intervals.

The setPaintTicks( ) method sets a boolean, which is used to activate or deactivate the slider’s tick marks. In some L&Fs, the slider changes from a rectangular shape to a pointer when tick marks are activated. This is often done to give the user a more accurate representation of where the slider falls.

You can create a Dictionary of Component objects to annotate the slider. Each entry in the Dictionary consists of two fields: an Integer key, which supplies the index to draw the various components, followed by the component itself. If you do not wish to create your own label components, you can use the createStandardLabels( ) method to create a series of JLabel objects for you. In addition, if you set the paintLabels property to true and give a positive value to the majorTickSpacing property, a set of labels that matches the major tick marks is automatically created.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class SliderExample extends JPanel {

    public SliderExample( ) {

        this.setLayout(new BorderLayout( ));
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);


        // We'll use just the standard numeric labels for now.

        add(slider, BorderLayout.CENTER);

    public static void main(String s[]) {
         JFrame frame = new JFrame("Slider Example");
         frame.setContentPane(new SliderExample( ));
         frame.pack( );

You may also like...