Using JSlider

Guest Posts Steven



A JSlider is a component that lets the user graphically select a value by sliding a knob within a bounded interval. The knob is always positioned at the points that match integer values within the specified interval.

The slider can show both major tick marks, and minor tick marks between the major ones. The number of values between the tick marks is controlled with setMajorTickSpacing and setMinorTickSpacing. Painting of tick marks is controlled by setPaintTicks.

Sliders can also print text labels at regular intervals (or at arbitrary locations) along the slider track. Painting of labels is controlled by setLabelTable and setPaintLabels.

A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value. If space is limited, a spinner is a possible alternative to a slider.

Here's the code:

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Example extends JFrame  implements ChangeListener {

    private JPanel contentPane;
    private JTextField textField;
    private JSlider slider1;

    /**
     * Create the frame.
     */
    public Example() {
        setTitle("Example");
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 286, 361);
        contentPane = new JPanel();
        setContentPane(contentPane);
        contentPane.setLayout(null);
        setVisible(true);
        GUI();
    }

    private void GUI() {
        slider1 = new JSlider();
        slider1 = new JSlider(JSlider.HORIZONTAL,0,50,25);//direction , min , max , current
        slider1.setMajorTickSpacing(10);
        slider1.setMinorTickSpacing(5);
        slider1.setPaintLabels(true);
        slider1.setPaintTicks(true);
        slider1.setBounds(28, 233, 200, 45);
        slider1.addChangeListener(this); //you add the change listener
        contentPane.add(slider1); // you add the slider to the frame

        JLabel lblCurrentValue = new JLabel("Current value:");
        lblCurrentValue.setBounds(28, 90, 77, 14);
        contentPane.add(lblCurrentValue);

        textField = new JTextField();
        textField.setEditable(false);
        textField.setBounds(112, 87, 34, 20);
        contentPane.add(textField);
        textField.setColumns(10);
    }

    public static void main(String[] args) {
        Example ex=new Example();
    }

    public void stateChanged(ChangeEvent e) {
        textField.setText(String.valueOf(slider1.getValue()));

    }
}


Here's the result:

You open the frame:
frame1

You slide the Jslider and the value will appear at the JTextField:
frame2

So that's how you use JSlider.