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

后端 未结 1 1218
滥情空心
滥情空心 2021-01-04 21:46

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

相关标签:
1条回答
  • 2021-01-04 22:38

    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 讨论(0)
提交回复
热议问题