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