在Java中通过单击鼠标移动球 [英] Move a ball on mouse click in Java

查看:197
本文介绍了在Java中通过单击鼠标移动球的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建经典的Breakout游戏,这是我的编程任务的一部分.我必须从用户的鼠标单击开始移动球.所以我正在使用鼠标监听器来实现这一目标.下面的代码只是我想要做的一个更小,更简单的版本.但是,它不会逐步移动球.在while循环执行完后,它只是将球显示在最终位置.

I'm trying to create the classic Breakout game as part of my programming assignment. I have to start moving the ball on a mouse click from the user. So I'm using a mouselistener to achieve that. The code below is just a smaller, simpler version of what I'm trying to do. But it does not move the ball in gradual steps. It just displays the ball at it's final position after the while loop is done executing.

import acm.graphics.*;
import acm.program.*;
import acm.util.*;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class BallMoveTest extends GraphicsProgram {

    public void run() {
        ball = new GOval(20,20);
        ball.setFilled(true);
        add(ball, 100, 100);

        addMouseListeners();
    }

    public void mouseClicked(MouseEvent e) {
        while (counter < 100) {
            moveBall();
            counter++;
            pause(20);
        }
    }

    public void moveBall(){
        ball.move(2, 2);
    }

    // Private instance variables
    private GOval ball;
    private int counter = 1;
}

但是此替代代码效果很好,但是不允许用户单击以开始移动球.

However this alternate code works wonderfully well, but does not allow the user to click to start the movement of the ball.

import acm.program.*;
import acm.graphics.*;

public class TestGOval extends GraphicsProgram {

    public void run() {
        int counter = 1;
        GOval ball = new GOval(20,20);
        ball.setFilled(true);
        add(ball,100,100);

        while (counter < 100) {
            ball.move(2, 2);
            counter++;
            pause(20);
        }

    }
}

有人可以指出我在这里做错了什么,更重要的是,为什么第一个代码块无法按预期工作?

Could someone point out what I'm doing wrong here and more importantly, why the first code block not work as intended?

PS:这是我的第一个问题,我是编程的新手.如果可以的话,请对我放松. :)

PS: This is my first question, and I'm a novice at programming. Go easy on me if you can. :)

推荐答案

可能只是您没有显示所有代码,但您应该拥有一个实现MouseListener的类.仅用鼠标单击的方法不足以让Java识别出这是您的意图.这里有一个更详细的教程: http://docs.oracle. com/javase/tutorial/uiswing/events/mouselistener.html

It may just be that you aren't showing all of your code, but you should have a class that implements MouseListener. Just having the mouse clicked method isn't enough for java to recognise that this is your intention; there's a tutorial here that has more detail: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

这篇关于在Java中通过单击鼠标移动球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆