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

nsc*_*010 3 java swing tooltip jbutton mousemotionevent

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

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

我该如何解决这个问题?

button1.addMouseMotionListener(this);
button2.addMouseMotionListener(this);
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 10

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

button.setTooltip("Manchester");
Run Code Online (Sandbox Code Playgroud)

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

button.setTooltip("<html>Manchester<br>53.4800° N, 2.2400° W</html>");
Run Code Online (Sandbox Code Playgroud)

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

button.setTooltip("<html><img src=" + getClass().getResource("/someimage") + "/>Manchester<br>53.4800° N, 2.2400° W</html>");
Run Code Online (Sandbox Code Playgroud)