java 将鼠标悬停在 JButton 上并显示一条消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14988996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hovering over JButtons and displaying a message
提问by nsc010
I want to hover over a number of JButtons on my GUI (map) and display the name of that location e.g. Manchester and London. I have the code working for one button, but it does not work for more than one button and prints the last out
message (as i have 10 buttons) for all button locations.
我想将鼠标悬停在 GUI(地图)上的多个 JButton 上并显示该位置的名称,例如曼彻斯特和伦敦。我的代码适用于一个按钮,但它不适用于多个按钮并打印out
所有按钮位置的最后一条消息(因为我有 10 个按钮)。
If button1
is true it then draws the text on the GUI in the specified area via my paintComponent()
method.
如果button1
为真,则通过我的paintComponent()
方法在指定区域的 GUI 上绘制文本。
How can i resolve this?
我该如何解决这个问题?
button1.addMouseMotionListener(this);
button2.addMouseMotionListener(this);
public void mouseMoved(MouseEvent arg0)
{
if(button1.contains(arg0.getPoint()))
{
button1 = true;
out = "test 1";
repaint();
}
if(!button1.contains(arg0.getPoint()))
{
b1 = false;
out = " ";
repaint();
}//same for all 10 buttons but change variables
}
回答by MadProgrammer
Why not use the tool tip API that already exists?
为什么不使用已经存在的工具提示 API?
button.setTooltip("Manchester");
You even use HTML text to produce formatted results.
您甚至可以使用 HTML 文本来生成格式化结果。
button.setTooltip("<html>Manchester<br>53.4800° N, 2.2400° W</html>");
If the images are embedded, you can even supply an image...
如果嵌入了图像,您甚至可以提供图像...
button.setTooltip("<html><img src=" + getClass().getResource("/someimage") + "/>Manchester<br>53.4800° N, 2.2400° W</html>");
回答by mKorbel
don't to use
MouseListener
orMosueMotionListener
fromJButton
, this method are correctly implemented inJButtons API
,there no reason, I can't found reason to use
repaint()
for this jobanother way is add
ChangeListener
toJButton
and take rellated event(s) from derivedButtonModel
for better help sooner post an SSCCE, short, runnable, compilable, just about
JFrame
with oneJButton
不要使用
MouseListener
或MosueMotionListener
来自JButton
,此方法在JButtons API
,没有理由,我找不到
repaint()
适合这份工作的理由另一种方式是添加
ChangeListener
到JButton
并采取源自rellated事件(一个或多个)ButtonModel
尽快发布SSCCE以获得更好的帮助,简短,可运行,可编译,只需
JFrame
一个JButton
回答by T Beatz
Well this answer is coolio for JDK 8 users, so try it out:
那么这个答案对于 JDK 8 用户来说是很酷的,所以试试看:
for regular text
对于常规文本
buttonyoumade.setToolTipText("Text you choose");
for html use
为 html 使用
anotherbuttonyoumade.setToolTipText("<html> any valid html code </html>");