I'm doing something where the ball bounces around the board from given coordinates but it's not working. No matter what I do, the ball always start moving from the top left.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board extends JPanel {
// Board dimensions
int width;
int height;
// Ball size
int radius = 4;
int diameter = radius * 2;
// Ball initial position
int X = radius + 239;
int Y = radius + 100;
// Direction
int dx = 3;
int dy = 3;
public Board() {
Thread thread = new Thread() {
public void run() {
while (true) {
repaint();
width = getWidth();
height = getHeight();
X = X + dx ;
Y = Y + dy;
if (X - radius < 0) {
dx = -dx;
X = radius;
} else if (X + radius > width) {
dx = -dx;
X = width - radius;
}
if (Y - radius < 0) {
dy = -dy;
Y = radius;
} else if (Y + radius > height) {
dy = -dy;
Y = height - radius;
}
try {
Thread.sleep(10);
} catch(InterruptedException ex) {}
}
}
};
thread.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval((int)(X - radius), (int)(Y - radius), (int)diameter, (int)diameter);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bouncing Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setContentPane(new Board());
frame.setVisible(true);
frame.setResizable(false);
}
}
Before adding the thread.start(); the ball is at the right position but as soon as I do, the ball goes back on the top left.
Help would be greatly appreciated!