Simple dynamic ToolTip text for JComponents

If you’re looking for a simple way to show a ToolTip on a JComponent based on a condition, you can do it by overriding the getToolTipText method.

By default the component will not show a ToolTip unless it is registered with the ToolTipManager. (Something that would have been done had you called setToolTipText)

JFrame frame = new JFrame("ToolTip Test");
 
JButton button = new JButton("Tip"){
    @Override
    public String getToolTipText() {
        if(isEven()){
            return "It's an even better time";
        } else {
            return "It's an odd time indeed";
        }
    }
 
    private boolean isEven() {
        return (System.currentTimeMillis() % 2) == 0;
    }
};
ToolTipManager.sharedInstance().registerComponent(button);
 
frame.add(button);
frame.setSize(70, 70);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
getToolTipText
This entry was posted in Programming and tagged , . Bookmark the permalink.

One Response to Simple dynamic ToolTip text for JComponents

  1. ToolTipManager.sharedInstance — that’s the ticket. been wondering a little bit about this for years…this dodges the silliness of setToolTipText(“foo”) in order to get a listener registered behind the scenes.

    Yay!

Leave a Reply

Your email address will not be published. Required fields are marked *