user2112303
user2112303

Reputation: 51

Ball doesn't move around screen

Hi i am creating a mini tennis game but for some reason the ball doesn't move on the screen. i have managed to create the bats and they both move. the ball requires to bounce off the bat and go in any directiong. Any Ideas??

Upvotes: 0

Views: 139

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209004

What you need for animation is a javax.swing.Timer. This is the basic construct

Timer(int delay, ActionListener listener)

For every so many milliseconds, the timer will fire an ActionEvent which will be listened for in the ActionListener you pass to it. So in your case, you'd want to call the ball.move() method to get the ball to animate.

The below code is all that I added, to the constructor of the MyDrawingPanel, and it animates fine. Note: I used your code from yesterday in a different question posted, so I can't guarantee the same results with your current code, if you've made changes.

    Timer timer = new Timer(20, new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            ball.move();
            repaint();
        }
    });
    timer.start();

You can of course have a separate button where you can call the timer.start() or timer.stop() and maybe have a reset button where you set the ball to a default location. But for now, the above should bring your animation to life.

Upvotes: 2

Related Questions