I think this behavior is controlled by the UI delegate of the component (SliderUI
). You can try another look & feel, or you can try to configure the one you use.
You can also install another UI delegate on your component.
See this real world example of customizing the behavior of a swing component.
Edit
I came up with a ugly hack that does the job. This code is completely dependant on the implementation details of the class BasicSliderUI
(which is used by most look & feels).
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JSlider;
import javax.swing.plaf.metal.MetalSliderUI;
public class MetalSnapSliderUI extends MetalSliderUI {
private MouseMotionListener myMouseMotionListener = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
trackListener.mouseDragged(e);
calculateThumbLocation();
slider.repaint();
}
public void mouseMoved(MouseEvent e) {
trackListener.mouseMoved(e);
}
};
@Override
protected void installListeners(JSlider slider) {
super.installListeners(slider);
slider.removeMouseMotionListener(trackListener);
slider.addMouseMotionListener(myMouseMotionListener);
}
@Override
protected void uninstallListeners(JSlider slider) {
super.uninstallListeners(slider);
slider.removeMouseMotionListener(myMouseMotionListener);
}
}
You will need to install this UI on the JSlider :
JSlider s = new JSlider();
s.setUI(new MetalSnapSliderUI());