Vikram
Vikram

Reputation: 227

Making text follow your cursor inside a JPanel

I'm trying to make a particular string of text follow the cursor inside the JPanel. I've created a class that extends JPanel and implements MouseMotionListener. The code does not seem to work. The text is shown, but it doesn't follow the cursor.

package followthemouse;

import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;

public class TheJPanel extends JPanel implements MouseMotionListener {

    private int x = 20;
    private int y = 20;

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawString("I love your cursor!", x, y);

    }


    @Override
    public void mouseMoved (MouseEvent me)
    {
        x = me.getX();
        y = me.getY();
        repaint();
    }

    @Override
    public void mouseDragged (MouseEvent me)
    {

    }


}

Here is what is in the main function :

package followthemouse;

import javax.swing.JFrame;

/**
 *
 * @author Vikram
 */
public class FollowTheMouse extends JFrame{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        TheJPanel y = new TheJPanel();
        JFrame x = new JFrame("The TITLE");
        x.add(y);
        x.setSize(400, 400);
        x.setVisible(true);

    }
}

What am I doing wrong?

Upvotes: 1

Views: 2215

Answers (2)

Aaron
Aaron

Reputation: 846

I think you need to add:

addMouseListener(y);
addMouseMotionListener(y);
  • plus coding this in a separate class would be better I think. You can also extend MouseInputAdapter instead of implementing MouseMotionListener.

Upvotes: 1

Peter
Peter

Reputation: 5224

You should add the listener to the panel.

Insert the following constructor:

public TheJPanel() {
    this.addMouseMotionListener(this);
}

Upvotes: 4

Related Questions