簡體   English   中英

動態更新當前顯示的工具提示

[英]Dynamically Update Tooltip Currently Displayed

我正在嘗試獲得一個顯示任務當前進度的工具提示。 所以,我想,雖然顯示的提示文本變化的提示。 但是,當我調用setToolTipText() ,顯示的文本保持不變,直到我從工具提示組件退出鼠標並再次輸入。 並且之前調用setToolTipText(null)不會改變任何東西。

實際上,即使在調用之間將工具提示重置為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();
            }
        });
    }
}

這是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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM