开发者

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 t开发者_JAVA百科hat 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!


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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜