You can set the position of the Java/Swing JSlider knob by dragging it with the left mouse button. But you can not set its position by clicking into the slider's running track, neither by left nor by right click. The left click moves the knob just a little by its increment value, which may require lots of clicks to get to the desired position. But the right mouse click is not used by JSlider, so why not use it for moving the knob to the click location?
Another idea would be to show tooltips according to the current mouse position over the slider. That means if you move the mouse e.g. over the value "2" of the slider, you would like to show a tooltip that says "Mouse is over the value of 2" (or something not so silly:-).
Move Knob to Right Mouse Click Location
All of the following applies to both horizontal and vertical sliders.
private JSlider createSlider() { final JSlider slider = new JSlider(); slider.addMouseListener(new MouseAdapter() { /** Moves the slider knob to the given event location when it was a right-mouse click.*/ @Override public void mouseClicked(MouseEvent e) { if (((JComponent) e.getSource()).isEnabled() && SwingUtilities.isRightMouseButton(e)) { final int sliderValue = new SliderMouseEventLocator(e).sliderValue; slider.setValue(sliderValue); } } }); return slider; }
So this was the mouse event catching, but what is SliderMouseEventLocator
?
public class SliderMouseEventLocator { /** Result of construction. */ public final Integer sliderValue; public SliderMouseEventLocator(MouseEvent e) { final JSlider slider = (JSlider) e.getSource(); final BasicSliderUI ui = (BasicSliderUI) slider.getUI(); final boolean horizontal = (slider.getOrientation() != SwingConstants.VERTICAL); this.sliderValue = horizontal ? ui.valueForXPosition(e.getX()) : ui.valueForYPosition(e.getY()); } }
This code converts the mouse click location to a slider value.
The mouse-event coordinate is relative to the slider, not relative to the window.
We can let BasicSliderUI
do the work.
You need a new SliderMouseEventLocator
for each arriving mouse event.
If you want to reuse that object, you would have to implement a mouse-event converter-method instead of the
immutable public final sliderValue
result field
(that must be evaluated at least on constructor execution).
Show Tooltip According to Mouse Location
Having the SliderMouseEventLocator
class,
it is easy to implement different tooltips according to mouse moves.
slider.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { final Integer sliderValue = new SliderMouseEventLocator(e).sliderValue; final String tooltip = getTextRepresentation(sliderValue); // TODO: implement getTextRepresentation slider.setToolTipText(tooltip); } });
Add this snippet to the createSlider()
method
and implement getTextRepresentation(sliderValue)
.
Hope this was helpful for the few remaining Swing programmers!