i have been trying to make a bouncing ball animation.I have got everything right except for one thing.
The ball goes off the screen once it hits the lower deck of the frame and the right hand side of it’s frame.
I have set the condition like :
if( x_Pos > frameWidth - ballRadius)
// turn the ball back
if( y_Pos > frameHeight - ballRadius)
// turn the ball back
But the ball disappears for a while when it hits the lower deck and the right deck of the frame.
Here is what happens eventually :


In the second pic ball has hit the lower deck and has disappeared for a while. Why this happens ?
In case this is my complete code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MovingBall2D extends JPanel{
int x_Pos=0;
int y_Pos=30;
int speedX=1;
int speedY=1;
int diameter=30;
int height=30;
int frameX=700;
int frameY=200;
int radius=diameter/2;
MovingBall2D() {
this.setSize(frameX,frameY);
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(x_Pos < 0) {
x_Pos = 0;
speedX = 1;
}
else if( x_Pos >= ( frameX - radius ) ) {
x_Pos = frameX - diameter;
speedX = -1;
}
if(y_Pos < 0) {
y_Pos = 0;
speedY = 1;
}
else if( y_Pos >= ( frameY - radius ) ) {
y_Pos = frameY - radius;
speedY = -1;
}
x_Pos = x_Pos + speedX;
y_Pos = y_Pos + speedY;
repaint();
}
};
new Timer(4,taskPerformer).start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.fillRect(0,0,frameX,frameY);
g.setColor(Color.red);
g.fillOval(x_Pos , y_Pos , diameter , height);
}
}
class Main2D {
Main2D() {
JFrame fr=new JFrame();
MovingBall2D o = new MovingBall2D();
fr.add(o);
fr.setSize(600,200);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new Main2D();
}
}
MovingBall2D.this.getHeight() is 173(because of panel padding,title,border etc.). That’s why
Just replace the if conidion like so:
The advantage of this is that even if the user resizes the window, the ball will hit the new window boundaries. Do the same for X axis.