I have a simple JSlider with an attached ChangeListerner. Here's the code:
JSlider slider = new JSlider();
slider.setMinorTickSpacing(2);
slider.setMajorTickSpacing(20);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
slider.setSnapToTicks(true);
slider.setOrientation(SwingConstants.VERTICAL);
contentPane.add(slider, BorderLayout.CENTER);
slider.addChangeListener(new SliderListener());
class SliderListener implements ChangeListener {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting()) {
System.out.println("boo");
}
}
}
As you can see, the code isn't doing much, all I want to do for now is make sure the event is only firing once, and hence my event is simply to print something to the Console within Eclipse.
But the above code is printing "boo" twice each time I change the Slider. I'm guessing this has got something to do with Mouse Release on Slider, but whatever it is, I want it to only fire the event once, and hence only print the word once.
How can I achieve that?
Thanks
Are you certain the listener is not added twice ? The following SSCCE works as expected on my machine (OS X, JDK7)
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.EventQueue;
public class SliderTest {
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame( );
final JSlider slider = new JSlider( 0, 100 );
frame.add( slider );
slider.addChangeListener( new ChangeListener() {
@Override
public void stateChanged( ChangeEvent e ) {
if ( !( slider.getValueIsAdjusting() ) ){
System.out.println( "SliderTest.stateChanged" );
}
}
} );
frame.pack();
frame.setVisible( true );
frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
}
} );
}
}