[英]Swing: How to create a custom JToolTip like widget that moves with the mouse
Java Swing question. Java Swing 问题。
I have a JPanel
which displays a graph.我有一个显示图形的JPanel
。 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.我想如果我知道如何将自定义JComponent
绝对定位在充当我的绘图画布的JPanel
,我的问题将得到解决。 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!任何其他解决方案(包括可能直接使用JToolTip
)也将非常受欢迎!
Override the getToolTipText(MouseEvent)
method to dynamically set the tool tip based on the mouse location.覆盖getToolTipText(MouseEvent)
方法以根据鼠标位置动态设置工具提示。
Edit:编辑:
If you want the tooltip to continually move with the mouse then you will also need to override the getToolTipLocation()
method.如果您希望工具提示随着鼠标持续移动,那么您还需要覆盖getToolTipLocation()
方法。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.