java处理鼠标单击,在Java中通过单击鼠标移动球

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: This is my first question, and I'm a novice at programming. Go easy on me if you can. :)

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值