I want to create a JSlider with labels, which have a tooltip.
JSlider slider = new JSlider();
JLabel label = new JLabel("First");
slider.setPaintLabels(true);
Hashtable<Integer, JLabel> labels = new Hashtable<Integer, JLabel>();
label.setToolTipText("Tooltip");
labels.put(new Integer(0), label);
slider.setLabelTable(labels);
But, this code does not work. I think it's because we can add tooltip to JSlider, and it "covered" all others.
Is there a method, how I can resolve my problem?
You would need to override the
getToolTipText(MouseEvent)
method.Then in the code you would need to determine the mouse position in the slider to determine the text to display. I've never tried it but you might be able to use the
BasicSliderUI
for this. It has methodsvalueForXPosition
andvalueForYPosition
which might help.Underlying reason for the obviously first try not working is that the labels are not added to the slider (as probably they should, given they are not too numerous anyway and the map is a map of real JLabels) but simply rendered on-the-fly in the paintHorizontal/VerticalLabel of BasicSliderUI. So Rob's advice the natural way to go: calculate if any of the labels is under the mousePosition and return its tooltip if available.
Astonishing, there is no public api (neither on JSlider nor on the ui delegate) to achieve the calculation of the label boundaries. What you would need is access to the x/yPositionForValue - but that's protected. So there are only dirty ways out
Would love to be proven wrong and see a clean implementation (without subclassing the ui-delegates :-)
This works fine. Here is the source link
Here is how I did it. It is a little rough but it works fine. :)
}