So I have this code that I made to make a ball bounce off the sides of the window no matter what the size of it, yet, I don't know what to do about this problem. Towards the bottom of the code, there is too parts that I have written. One updates with the resizing of the window and has the ball bounce off accordingly and the other has it bounce on invisible walls so the size of the windows doesn't affect it.
The problem I'm having with it is the fact that I want to have it start off in different places and eventually get it to start off at the bottom of the screen so I can add gravity and make it look like a regular bouncing ball. When i run the one with numbers I can set the ball to start where I want it to but when I run the one with getWidth and getHeight, no matter what numbers I put, it starts off at the corner of the screen on the top left hand corner. Can someone please help me and explain to me what is wrong with my code?
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bouncing.ball; /** * * @author Marlin */ import javax.swing.*; import java.awt.*; public class BouncePanel extends JPanel { //location of bouncing ball private int x; private int y; private int dx = 5; private int dy = 5; BouncePanel() { x = 100; y = 400; AnimationThread animethread = new AnimationThread(this); animethread.start(); } public void paintComponent(Graphics g) { //clear screen super.paintComponent(g); g.setColor(Color.BLUE); g.fillOval(x, y, 40, 40); } public void update() { x += dx; y += dy; if (x < 0) { x = 0; dx = -dx; } if (x + 40 >= getWidth()) { x = getWidth() - 40; dx = -dx; } if (y < 0) { y = 0; dy = -dy; } if (y + 40 >= getHeight()) { y = getHeight() - 40; dy = -dy; } // if(x < 0){ // x = 0; // dx = -dx; // } // if (x + 30 >= 400) { // x = 400 - 30; // dx = -dx; // } // if (y < 0) { // y = 0; // dy = -dy; // } // if (y + 30 >= 400) { // y = 400 - 30; // dy = -dy; // } repaint(); } }