Hovering over JButtons and displaying a message

删除回忆录丶 提交于 2019-12-04 04:33:51

问题


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.

If button1 is true it then draws the text on the GUI in the specified area via my paintComponent() method.

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
}

回答1:


Why not use the tool tip API that already exists?

button.setTooltip("Manchester");

You even use HTML text to produce formatted results.

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



回答2:


  • don't to use MouseListener or MosueMotionListener from JButton, this method are correctly implemented in JButtons API,

  • there no reason, I can't found reason to use repaint() for this job

  • another way is add ChangeListener to JButton and take rellated event(s) from derived ButtonModel

  • for better help sooner post an SSCCE, short, runnable, compilable, just about JFrame with one JButton




回答3:


Well this answer is coolio for JDK 8 users, so try it out:

for regular text

buttonyoumade.setToolTipText("Text you choose");

for html use

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


来源:https://stackoverflow.com/questions/14988996/hovering-over-jbuttons-and-displaying-a-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!