摇摆:如何创建一个自定义的JToolTip像小部件,该小部件随鼠标移动 [英] Swing: How to create a custom JToolTip like widget that moves with the mouse

查看:40
本文介绍了摇摆:如何创建一个自定义的JToolTip像小部件,该小部件随鼠标移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java Swing问题.

Java Swing question.

我有一个显示图形的 JPanel .当我将鼠标移到该图上时,我希望某些信息显示在随鼠标移动的类似工具提示的小部件上.我怎样才能最好地实现这一目标?

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?

我想,如果我知道如何将自定义的 JComponent 完全放在用作我的绘图画布的 JPanel 中,我的问题就可以解决.然后,我可以捕获鼠标移动的事件并重新定位/更新小部件.任何其他解决方案(包括可能直接使用 JToolTip 的解决方案)也将非常受欢迎!

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!

推荐答案

重写 getToolTipText(MouseEvent)方法以根据鼠标位置动态设置工具提示.

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

如果您希望工具提示继续用鼠标移动,则还需要重写 getToolTipLocation()方法.

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

这篇关于摇摆:如何创建一个自定义的JToolTip像小部件,该小部件随鼠标移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆