getValueIsAdjusting()
method
to see if the user is still moving the knob and hasn't
released the mouse button. See example below.
stateChanged(...)
method, which has a ChangeEvent
parameter.
You can call the ChangeEvent
getSource()
method to
get the slider which caused this event (obviously it is the same
slider that you are attaching the listener to). The example below
gets the value only after the user has stopped moving
the knob on the slider and released the mouse button.
The JSlider method getValueAdjusting()
is
true if the user is still has the mouse button down, and false if the user has
released it.
It calls setSomething
, a user defined method,
to change the drawing.
Most of this code is is the same for all sliders, and that only the slider
name and the statements in the inner part need to change.
slider.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); // get the slider if (!source.getValueIsAdjusting()) { val = source.getValue(); // get slider value picture.setSomething(val); // picture must repaint itself } } });
JSlider happiness = new JSlider(JSlider.VERTICAL, 0, 20, 10); happiness.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { JSlider source = (JSlider)e.getSource(); if (!source.getValueIsAdjusting()) { smile = source.getValue(); // this only sets smile // should do something with this value now. } } }); happiness.setMajorTickSpacing(10); happiness.setMinorTickSpacing(1); happiness.setPaintTicks(true); happiness.setBorder(BorderFactory.createEmptyBorder(0,0,10,0)); content.add(happiness);