Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a tooltip on a mouse click

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

like image 267
user935339 Avatar asked Sep 08 '11 18:09

user935339


1 Answers

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();
            }
        });
    }
}
like image 132
camickr Avatar answered Sep 27 '22 18:09

camickr