How to show a tooltip on a mouse click

user935339 picture user935339 · Sep 8, 2011 · Viewed 10.6k times · Source

I have a JTreeTable and have successfully implemented a MouseMotionListener to show a tooltip whenever the mouse is over one of the cells. However when clicking on the cell the tooltip does not show up. I've tried several things like setting the text on the mouseClicked and mouseReleased events but that doesn't work. I found this code -

Action toolTipAction = treeTable.getActionMap().get("postTip");

if(toolTipAction != null){

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

to use in the mouseReleased method, which does make the tooltip popup, but it's then in the wrong position. So next i tried overriding the getTooltipLocation method on the JTreeTable, and this works fine for mouseMoved events but doesn't get called with the above method. Can anyone shed some light on how to do this?

Thanks Andy

Answer

camickr picture camickr · Sep 9, 2011

You can use the following approach to show the tooltip (there will be a slight delay). Then you can override the getToolTipLocation() method since a MouseEvent will now be generated:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ToolTipOnRelease extends JPanel
{
    public ToolTipOnRelease()
    {
        JLabel label = new JLabel( "First Name:" );
        add( label );

        JTextField textField = new JTextField(15);
        add( textField );

        MouseListener ml = new MouseAdapter()
        {
            public void mouseReleased(MouseEvent e)
            {
                JComponent component = (JComponent)e.getSource();
                component.setToolTipText("Mouse released on: " + component.getClass().toString());

                MouseEvent phantom = new MouseEvent(
                    component,
                    MouseEvent.MOUSE_MOVED,
                    System.currentTimeMillis(),
                    0,
                    0,
                    0,
                    0,
                    false);

                ToolTipManager.sharedInstance().mouseMoved(phantom);
            }
        };

        label.addMouseListener( ml );
        textField.addMouseListener( ml );
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("ToolTipOnRelease");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new ToolTipOnRelease() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}