[英]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
MouseListener
或MosueMotionListener
,這個方法在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.