如何使用鼠标运动监听器制作移动球

时间:2018-05-29 19:59:39

标签: java mouseevent mousemotionevent

 addMouseMotionListener(new MouseAdapter() {
        public void mouseMoved(MouseEvent e) {
            relativeX = e.getX();
            relativeY = e.getY();
            System.out.println(relativeX + "," + relativeY);
            System.out.println(x + "," + y);
            x = x + speedX;
            y = y + speedY;
            repaint();
            if (x > relativeX) {
                speedX = speed * -1;
            } else if (x < relativeX) {
                speedX = speed;
            }
            if (y > relativeY) {
                speedY = speed * -1;
            } else if (y < relativeY) {
                speedY = speed;
            }
        }
    });

大家好,我创造了一个鼠标动作监听器,球将按照鼠标移动的方向。但是,一旦我停止移动鼠标,球就会停止移动。尽管我的鼠标光标与球的位置之间存在相当大的距离,但是球只是拒绝移动到我的鼠标位置。我认为这是因为我的动作监听器停止工作,因为我不再移动鼠标了。有没有人对如何强迫球移动到我的鼠标的确切位置有任何想法。(第一次询问堆栈溢出希望每个人都没有我的语法)

 private void doDrawing(Graphics g) {
    radius = 20;
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(red);
    g2d.fillOval((int) x, (int) y, radius, radius);
}

这就是移动的球。

0 个答案:

没有答案
相关问题