tags:

views:

140

answers:

4

Is there an elegantish way in Swing to find out if there are any tooltips currently being displayed in my frame?

I'm using custom tooltips, so it would be very easy to set a flag in my createToolTip() method, but I can't see a way to find out when the tooltip is gone.

ToolTipManager has a nice flag for this, tipShowing, but of course it's private and they don't seem to offer a way to get to it. hideWindow() doesn't call out to the tooltip component (that I can tell), so I don't see a way there.

Anyone have any good ideas?

Update: I went with reflection. You can see the code here:

private boolean isToolTipVisible() {
 // Going to do some nasty reflection to get at this private field.  Don't try this at home!
 ToolTipManager ttManager = ToolTipManager.sharedInstance();
 try {
  Field f = ttManager.getClass().getDeclaredField("tipShowing");
  f.setAccessible(true);

  boolean tipShowing = f.getBoolean(ttManager);

  return tipShowing;

 } catch (Exception e) {
  // We'll keep silent about this for now, but obviously we don't want to hit this
  // e.printStackTrace();
  return false;
 }
}
+1  A: 

It appears that the isEnabled() property of the hideTipAction is directly tied to the tipShowing boolean. You could try this:

public boolean isTooltipShowing(JComponent component) {
    AbstractAction hideTipAction = (AbstractAction) component.getActionMap().get("hideTip");
    return hideTipAction.isEnabled();
 }

You probably want to do some sanity checking for nulls, etc. But this should get you pretty close.

EDIT, to your responses:

Short of some ugly reflection code, I don't think you have much choice. You cannot subclass ToolTipManager because of the package private constructor, and the showTipWindow() and hideTipWindow() are also package private, so the Adapter pattern is out as well.

James Van Huis
A: 

It looks like that is going to require looping over all of the components to see if they have a tooltip. I'm looking for a global value. It may be that a loop is doable, but it seems inefficient.

David Irwin
A: 

That's too bad. After an internal discussion, "ugly reflection" was what we came up with as well, but I was hoping someone out there had a better idea.

David Irwin
A: 

Since you already have your own createToolTip(), maybe you can try something like this :)

public JToolTip createToolTip() {
  JToolTip tip = super.createToolTip();
  tip.addAncestorListener( new AncestorListener() {
    public void ancestorAdded( AncestorEvent event ) {
      System.out.println( "I'm Visible!..." );
    }

    public void ancestorRemoved( AncestorEvent event ) {
      System.out.println( "...now I'm not." );
    }

    public void ancestorMoved( AncestorEvent event ) { 
      // ignore
    }
  } );
  return tip;
}