2012-10-10 73 views
3

我正在嘗試獲取顯示任務當前進度的工具提示。所以我希望工具提示文字改變,同時顯示工具提示。但是,當我撥打setToolTipText()時,顯示的文本保持不變,直到我從工具提示組件中退出鼠標並再次輸入。之前撥打setToolTipText(null)不會改變任何內容。當前顯示的動態更新工具提示

回答

4

事實上,即使將調用的工具提示重置爲null,它也不會自行更新。

到目前爲止,我發現的唯一技巧是模擬鼠標移動事件並將其轉發到TooltipManager上。這讓他認爲鼠標已經移動,並且工具提示必須重新定位。不漂亮,但非常有效。

看一看顯示從0到100%的進度此演示代碼:

import java.awt.MouseInfo; 
import java.awt.Point; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.MouseEvent; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 
import javax.swing.Timer; 
import javax.swing.ToolTipManager; 

public class TestTooltips { 

    protected static void initUI() { 
     JFrame frame = new JFrame("test"); 
     final JLabel label = new JLabel("Label text"); 
     frame.add(label); 
     frame.pack(); 
     frame.setVisible(true); 
     Timer t = new Timer(1000, new ActionListener() { 

      int progress = 0; 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (progress > 100) { 
        progress = 0; 
       } 
       label.setToolTipText("Progress: " + progress + " %"); 
       Point locationOnScreen = MouseInfo.getPointerInfo().getLocation(); 
       Point locationOnComponent = new Point(locationOnScreen); 
       SwingUtilities.convertPointFromScreen(locationOnComponent, label); 
       if (label.contains(locationOnComponent)) { 
        ToolTipManager.sharedInstance().mouseMoved(
          new MouseEvent(label, -1, System.currentTimeMillis(), 0, locationOnComponent.x, locationOnComponent.y, 
            locationOnScreen.x, locationOnScreen.y, 0, false, 0)); 
       } 
       progress++; 
      } 
     }); 
     t.start(); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       initUI(); 
      } 
     }); 
    } 
} 
+0

只是一個小問題。工具提示的初始延遲必須小於文本的更新延遲。 – paranoia25

-2

這裏的Guillaume Polet的答案的簡化版本,這是自包含在一個單一的方法。此代碼假定以前稱之爲component.setToolTip("...");。此代碼不會而不是顯示如何定期更新工具提示以顯示進度。

public static void showToolTip(JComponent component) 
{ 
    ToolTipManager manager; 
    MouseEvent event; 
    Point point; 
    String message; 
    JComponent component; 
    long time; 

    manager = ToolTipManager.sharedInstance(); 
    time = System.currentTimeMillis() - manager.getInitialDelay() + 1; // So that the tooltip will trigger immediately 
    point = component.getLocationOnScreen(); 
    event = new MouseEvent(component, -1, time, 0, 0, 0, point.x, point.y, 1, false, 0); 

    ToolTipManager. 
     sharedInstance(). 
     mouseMoved(event); 
}