# Thread: Flipping the direction on the bouncing ball problem!

1. Member
Join Date
Jun 2010
Posts
12
Rep Power
0

## Flipping the direction on the bouncing ball problem!

Hi all, I'm currently trying to complete the famous basic program "Bouncing Ball". For those who are not familiar with this problem. Here is the spec:

- write a swing component that extends JPanel
- contains a ball with x and y coords and with vx, vy random velocities
- constructor has a thread that updates the position of the ball
- if the ball hits any of the edges flip the sign of the velocity accordingly
- paintComponent that draws the ball at its location

I have completed most of my code but cannot seem to figure out how to make it bounce of the "walls"... The ball seems to get stuck at the top right corner and it just continuously bounces off of the corner.

Here is my code:

import java.util.Random;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class BouncingBall extends JPanel
{
private double x,y;
private double vx,vy;
private static final Random rng = new Random();
private volatile boolean running = true;

public BouncingBall(){
this.setPreferredSize(new Dimension(300,300));
this.setBackground(Color.BLACK);
Random rng = new Random();
x = 135;
y = 135;

vx = rng.nextInt(3)+1;
vy = rng.nextInt(3)+1;

new Thread(new Runnable() {
public void run() {
while(running) {
try { Thread.sleep(40); } catch(InterruptedException e) { }
draw();
repaint();
}
}
}).start();

}

public void draw(){
x -= vx;
y -= vy;
if (y>300 || y<0){
y = -y;
}

if (x>300 || x<0){
x = -x;
}
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASIN G,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fill(new Ellipse2D.Double(x, y,30,30));
}

public static void main (String[] args){
JFrame f = new JFrame("Bouncing Ball");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );
f.setVisible(true);
f.pack();
}
}

Any help would be appreciated. Thanks!

2. Please do not double post your questions as it is considered rude, and for good reason as you then risk splitting the discussion unnecessarily leading to duplication of effort. I'm locking this thread.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•