简体   繁体   English

如何制作跟随鼠标cursor的笑脸

[英]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.我正在尝试使用 AWT 和 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.我试图实现 MouseMotionListener,但我不确定我做错了什么,因为我看不到它在工作。 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.我想知道我做错了什么。

You're not updating the smiley face when the mouse is moved with the appropriate x and y coordinates.当鼠标移动到适当的 x 和 y 坐标时,您不会更新笑脸。 Set the private int x, y;设置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.一旦鼠标移动,变量就会更新,笑脸也会移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM