繁体   English   中英

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

[英]Hovering over JButtons and displaying a message

我想将鼠标悬停在我的GUI(地图)上的一些JButton上,并显示该位置的名称,例如曼彻斯特和伦敦。 我的代码为一个按钮的工作,但它并不适用于多个按钮的工作并打印最后out的消息(如我有10个按钮),所有按钮的位置。

如果button1为true,则通过paintComponent()方法在指定区域的GUI上绘制文本。

我该如何解决这个问题?

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
}

为什么不使用已经存在的工具提示API?

button.setTooltip("Manchester");

您甚至可以使用HTML文本生成格式化结果。

button.setTooltip("<html>Manchester<br>53.4800° N, 2.2400° W</html>");

如果嵌入了图像,您甚至可以提供图像......

button.setTooltip("<html><img src=" + getClass().getResource("/someimage") + "/>Manchester<br>53.4800° N, 2.2400° W</html>");
  • 不要使用JButton MouseListenerMosueMotionListener ,这个方法在JButtons API中正确实现,

  • 没有理由,我找不到使用repaint()来完成这项工作的理由

  • 另一种方法是将ChangeListener添加到JButton并从派生的ButtonModel获取相关的事件

  • 更快地发布SSCCE ,简短,可运行,可编译,只需使用一个JButton JFrame

那么这个答案对于JDK 8用户来说很酷,所以试试吧:

对于常规文本

buttonyoumade.setToolTipText("Text you choose");

用于HTML使用

anotherbuttonyoumade.setToolTipText("<html> any valid html code </html>");

暂无
暂无

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

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