Domanda

I want to have a dynamic tooltip for my JButton, so I used something like this to overwrite the getToolTipText() method...

JButton myJButton=new JButton("My Button"){
    public String getToolTipText(MouseEvent evt){
        ToolTipManager.sharedInstance().setInitialDelay(100);
        ToolTipManager.sharedInstance().setDismissDelay(60000);

        return "Test Tip Here";
        }  // Return plain text now, will be replaced by calculateTipText() later
    };

When I have this code, no tooltip is being displayed at all.

However, if I add another line like this...

myJButton.setToolTipText("Hi");

After this point, the tooltip will be displayed correctly as Test Tip Here.

Why doesn't my tooltip work until I call setToolTipText()?

È stato utile?

Soluzione

When you call setToolTipText(), listeners are registered on your JButton that allow the tooltip to be displayed. These listeners are only registered on the JButton when you call setToolTipText(), because there's no use listening for tooltips on all JButtons when only a small subset of them actually have a tool tip value set.

Overwriting the getToolTipText() method will return the String you specify, but only after you register the listeners on the JButton first (by calling the setToolTipText() method).

Refer to the JButton source code here where you can see that it sets the value and then registers the listeners in the ToolTipManager. You may be able to register the listeners yourself to achieve what you want, such as by calling this after you create the button...

ToolTipManager.sharedInstance().registerComponent(myJButton);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top