Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing: How to create a custom JToolTip like widget that moves with the mouse

Java Swing question.

I have a JPanel which displays a graph. When I move the mouse over this graph, I want certain information to be displayed on a tooltip-like widget that moves with the mouse. How can I best implement this?

I guess my problem will be solved if I know how to position a custom JComponent absolutely within the JPanel that acts as my drawing canvas. I could then trap the mouse moved event and reposition/update the widget. Any other solution (including possibly using JToolTip directly) would also be very much welcome!

like image 819
ARV Avatar asked Aug 21 '11 14:08

ARV


1 Answers

Override the getToolTipText(MouseEvent) method to dynamically set the tool tip based on the mouse location.

Edit:

If you want the tooltip to continually move with the mouse then you will also need to override the getToolTipLocation() method.

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

public class ToolTipPanel extends JPanel
{
    public ToolTipPanel()
    {
        setPreferredSize( new Dimension(200, 200) );
        setToolTipText("");
    }

    public void paintComponent(Graphics g)
    {
        g.setColor( Color.red );
        g.fillRect(0, 0, 100, 200);
        g.setColor( Color.blue );
        g.fillRect(100, 0, 100, 200);
    }

    public String getToolTipText(MouseEvent e)
    {
        if (e.getX() < 100)
            return "red";
        else
            return "blue";
    }

    public Point getToolTipLocation(MouseEvent e)
    {
        Point p = e.getPoint();
        p.y += 15;
        return p;
//      return super.getToolTipLocation(e);
    }

    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.getContentPane().add( new ToolTipPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
like image 82
camickr Avatar answered Nov 15 '22 18:11

camickr