The ball leaves the screen

I'm trying to make a ball animation. Everything is correct with the exception of one thing. The ball leaves the screen when it hits the lower deck of the frame and the right side of its frame.

I set the condition as:

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's what happens in the end: enter image description here

enter image description here

In the second pic ball, the ball hit the lower deck and disappeared for a while. Why is this happening?

If this is my full 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();
     }
     }  
+3
source share
4 answers

MovingBall2D.this.getHeight () - 173 (due to fill, title, border, etc.). That's why

Just replace if conidion as follows:

    else if( y_Pos >= ( MovingBall2D.this.getHeight()- radius ) )
    {
        y_Pos = MovingBall2D.this.getHeight() - radius;
        speedY = -1;
    }

, , . X.

+1

, JFrame 200 , , ( ).

, (xpos, ypos) (xpos+diameter,ypos+diameter), y_Pos > frameHeight - ballDiameter y_Pos > frameHeight - ballRadius.

+4

, (700) (600). JPanel.getWidth() JPanel.getHeight(), .

+2

, Tuple2D, . java, -, google .

0

All Articles