1

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);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
helpdesk
  • 1,984
  • 6
  • 32
  • 50
  • 3
    don't use Java reserved words as class names use MySlider instead of Slider, don't extends JFrame because this is direct road to the problems, GUI rellated code in the main void should be wrapped into invokeLater, for more read [Initial Threads](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html) – mKorbel Mar 28 '12 at 16:41

2 Answers2

5

See addChangeListener(ChangeListener), as well as How to Use Sliders & How to Write a Change Listener.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    @henry joseph maybe important, maybe not, you have look at `BoundedRangeModel` and add `ChangeListener` to this model – mKorbel Mar 28 '12 at 17:02
3

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

Spin slider

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045