ab11 ab11 - 6 months ago 16
Java Question

Java Swing: How to be notified if tool tip is about to become visible?

I have a lot of components that set tool tips with

JComponent.setToolTipText(...)
. However, these tool tips change often based on many events. I could make a setToolTipText(...) call each time one of these events occur; but I would much prefer to simply have a tool tip listener that notifies me when a tip is about to show, so that I can update the tip, if needed. I can't find anyway to assign a listener to the tool tip, am I missing one?

*Note, my solution needs to be Java 1.4.2 compliant.

Answer

Actually found a decent solution: override JComponent.getToolTipText().

One disturbing nuance to this, this is the code from JComponent.setToolTipText():

  public void setToolTipText(String text) {
        String oldText = getToolTipText();
        putClientProperty(TOOL_TIP_TEXT_KEY, text);
        ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
        if (text != null) {
        if (oldText == null) {
                toolTipManager.registerComponent(this);
        }
        } else {
            toolTipManager.unregisterComponent(this);
        }
    }

So, if you override getToolTipText to return some dynamic value, it better return null the first time it is called, or your tool tip will not get registered with the ToolTipManager.