JSlider 标签中的工具提示
我想创建一个带有标签的 JSlider,其中有一个工具提示。
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);
但是,这段代码不起作用。我认为这是因为我们可以向 JSlider 添加工具提示,并且它“覆盖”了所有其他工具提示。
有什么方法可以解决我的问题吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要重写
getToolTipText(MouseEvent)
方法。然后在代码中,您需要确定滑块中的鼠标位置以确定要显示的文本。我从未尝试过,但您也许可以使用
BasicSliderUI
来实现此目的。它的方法valueForXPosition
和valueForYPosition
可能会有所帮助。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.显然第一次尝试不起作用的根本原因是标签没有添加到滑块中(可能应该添加到滑块中,因为它们并没有太多并且地图是真实 JLabels 的地图)但是简单地在 BasicSliderUI 的 PaintHorizontal/VerticalLabel 中动态渲染。因此,Rob 的建议是自然的方法:计算是否有任何标签位于 mousePosition 下,并返回其工具提示(如果可用)。
令人惊讶的是,没有公共 api(无论是在 JSlider 上还是在 ui delegate 上)来实现标签边界的计算。您需要的是访问 x/yPositionForValue - 但这是受保护的。因此,只有肮脏的方法可以
希望被证明是错误的并看到一个干净的实现(无需子类化 ui 代表:-)
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 :-)
我是这样做的。它有点粗糙,但效果很好。 :)
}
Here is how I did it. It is a little rough but it works fine. :)
}
这很好用。这是源链接
This works fine. Here is the source link