Manindra Moharana
Manindra Moharana

Reputation: 1054

Toggling Dynamic Tooltip - java swing

I have a swing component, for which I've overridden getToolTipText(MouseEvent) to get custom tooltips for different mouse locations within the component. What I want to achieve is that tooltips must not be shown for certain mouse locations.

I tried returning null inside getToolTipText(MouseEvent) when mouse is in those invalid locations, but that causes a null pointer exception. If I return an empty string, I get the expected behaviour on OS X (no tooltip displayed). But an empty tooltip gets displayed on Linux.

public String getToolTipText(MouseEvent evt) {
    if(mouseInCorrectRegion(evt)) {
      return "A tooltip!";
    }
    else {
      //No tooltip displayed on OS X, but 
      //empty tooltip displayed on Linux
      return ""; 

      // return null; //Causes NPE randomly 
    }
}

So, how do I dynamically enable/disable tooltips based on mouse location within the component? Should I try using ToolTipManager.sharedInstance().registerComponent() and unregisterComponent() inside the component's mouseMoved()?

Upvotes: 1

Views: 856

Answers (1)

VGR
VGR

Reputation: 44414

According to the Swing tutorial and the documentation for JComponent.setToolTipText, passing null to setToolTipText will turn off the tooltip, so you can do this:

@Override
public String getToolTipText(MouseEvent event) {
    if (mouseInCorrectRegion(event)) {
        setToolTipText("A tooltip");
    } else {
        setToolTipText(null);
    }
    return super.getToolTipText(event);
}

Upvotes: 2

Related Questions