Wandondi
Wandondi

Reputation: 3

How to make smiley face that follows the cursor of the mouse

I'm trying to draw a SMiley Face that moves when the mouse is moved or dragged using AWT and Swing.

I have tried to implement the MouseMotionListener but I'm not sure what I'm doing wrong because I don't see it working. Below is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SmileyFace extends JPanel implements MouseMotionListener {
    private int x, y;
    public SmileyFace() {
        addMouseMotionListener(this);
    }
    
    public void mouseDragged(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();
    }
    
    public void mouseMoved(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.YELLOW);
        g.fillOval(100, 100, 200, 200);
        g.setColor(Color.BLACK);
        g.drawOval(100, 100, 200, 200);
        g.drawOval(155, 155, 10, 10);
        g.drawOval(230, 155, 10, 10);
        g.drawArc(150, 200, 100, 50, 0, -180);
    }    
}

I wish to know what I've not done correctly.

Upvotes: 0

Views: 142

Answers (1)

Trooper Z
Trooper Z

Reputation: 1661

You're not updating the smiley face when the mouse is moved with the appropriate x and y coordinates. Set the private int x, y; to the coordinates that you would like to be the default and replace the coordinates in the circle drawing section with those (for the elements like the eyes and mouth, add/subtract appropriate amounts onto their values). Once the mouse moves, the variables should be updated and the smiley will be moved.

Upvotes: 1

Related Questions