Search code examples
javaswingtooltipjbuttonfocuslistener

JButton show tooltip programically: actionMap.get("postTip") is null


I need to programically show tooltip for my button2 when it gets focus. (I press Tab as intially focus at button1)

            JButton button = new JButton("Button 1");

            JButton button2 = new JButton("Button 2");
            button2.setToolTipText("tooltip2");
            button2.addFocusListener(new FocusListener());

I refer the code by @camickr

private class FocusListener extends FocusAdapter {
 public void focusGained(FocusEvent e)
 {
    JComponent component = (JComponent)e.getSource();
    Action toolTipAction = component.getActionMap().get("postTip");

but toolTipAction is set null.

I have printed all the entries of ActionMap using this code

        ActionMap actionMap = component.getActionMap();
        Object[] actionMapKeys = actionMap.allKeys();

        for (int i = 0; i < actionMapKeys.length; i++) {
            Object key = actionMapKeys[i];
            System.out.println(key.toString() + " : " + actionMap.get(key).toString());
        }

This is what it gives me

pressed : javax.swing.plaf.basic.BasicButtonListener$Actions@49cf9f
released : javax.swing.plaf.basic.BasicButtonListener$Actions@1de0b5e

So how can I call this code if I got toolTipAction null?

ActionEvent postTip = new ActionEvent(component, ActionEvent.ACTION_PERFORMED, "");
toolTipAction.actionPerformed(postTip);

Solution

  • actuall I want to show tooltip on some network event, which has nothing to do with mouse. but I have started experiments with focus gained by Tab key

    • use JWindow (undecorated JDialog) or JLabel instead of ToolTip, examples for JLabel by @Guillaume Polet and here

    • you can to lay this container to the Mouse Cursor possition or to stick to absolute coordinates, Point to the visible GUI

    • standard could be (can be annoying) see SystemTray and TrayIcon#displayMessage