Search code examples
javamouseeventmouseclick-eventbreakoutacm-java-libraries

Move a ball on mouse click in 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. :)


Solution

  • 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