繁体   English   中英

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

[英]How to make smiley face that follows the cursor of the mouse

我正在尝试使用 AWT 和 Swing 绘制一个在移动或拖动鼠标时移动的笑脸。

我试图实现 MouseMotionListener,但我不确定我做错了什么,因为我看不到它在工作。 下面是代码:

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

我想知道我做错了什么。

当鼠标移动到适当的 x 和 y 坐标时,您不会更新笑脸。 设置private int x, y; 到您希望成为默认坐标的坐标,并将圆形绘图部分中的坐标替换为那些坐标(对于眼睛和嘴巴等元素,在它们的值上添加/减去适当的量)。 一旦鼠标移动,变量就会更新,笑脸也会移动。

暂无
暂无

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

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