Question

How can I add an event to this code such that if i drag the slider, the number is displayed. Please, let me know as I am new to Java..

import javax.swing.*;

public class Slider extends JFrame {

    JSlider pickNum = new JSlider(JSlider.HORIZONTAL, 0, 30, 5);

    public Slider() {
        super("Slider");
        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        pickNum.setMajorTickSpacing(10);
        pickNum.setMinorTickSpacing(1);
        pickNum.setPaintTicks(true);
        pickNum.setPaintLabels(true);
        getPointedValue();
        this.add(pickNum);
        this.setVisible(true);
    }

    public final int getPointedValue() {
        int value;
        value = pickNum.getValue();
        return value;
    }

    public static void main(String[] args) {
        Slider frame = new Slider();
        int i;
        i = frame.getPointedValue();
        System.out.println("current value is:" + i);
    }
}
Was it helpful?

Solution

As a concrete example using ChangeListener, SpinSlider shows how to connect a JSlider and a JSpinner.

Spin slider

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top