简体   繁体   English

将鼠标悬停在JButtons上并显示一条消息

[英]Hovering over JButtons and displaying a message

I want to hover over a number of JButtons on my GUI (map) and display the name of that location eg Manchester and London. 我想将鼠标悬停在我的GUI(地图)上的一些JButton上,并显示该位置的名称,例如曼彻斯特和伦敦。 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. 我的代码为一个按钮的工作,但它并不适用于多个按钮的工作并打印最后out的消息(如我有10个按钮),所有按钮的位置。

If button1 is true it then draws the text on the GUI in the specified area via my paintComponent() method. 如果button1为true,则通过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
}

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>");
  • don't to use MouseListener or MosueMotionListener from JButton , this method are correctly implemented in JButtons API , 不要使用JButton MouseListenerMosueMotionListener ,这个方法在JButtons API中正确实现,

  • there no reason, I can't found reason to use repaint() for this job 没有理由,我找不到使用repaint()来完成这项工作的理由

  • another way is add ChangeListener to JButton and take rellated event(s) from derived ButtonModel 另一种方法是将ChangeListener添加到JButton并从派生的ButtonModel获取相关的事件

  • for better help sooner post an SSCCE , short, runnable, compilable, just about JFrame with one JButton 更快地发布SSCCE ,简短,可运行,可编译,只需使用一个JButton JFrame

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>");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM