Java中的Bouncing Ball保持在界限内

时间:2016-04-14 01:29:50

标签: java swing animation graphics

我试图让这个Bouncing Ball程序让球在窗口中反弹,但无论我做什么,它都会反弹一次,然后无限期地从屏幕上移开。我该怎么做才能让它留在屏幕上?

/*
* File: BouncingBall.java
* This program graphically simulates a bouncing ball. 
*
*
*/
import java.awt.event.*;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.Timer;

public class BouncingBall
{
   public static void main()
   {
      JFrame frame = new JFrame( "Bouncing Ball" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

      BallPanel bp = new BallPanel(); 
      frame.add( bp );
      frame.setSize( 600, 300 ); // set frame size
      frame.setVisible( true ); // display frame
   } // end main
}


// class BallPanel
class BallPanel extends JPanel implements ActionListener
{
   private int delay = 15;
   protected Timer timer;

   private int x = 0;            // x position
   private int y = 0;            // y position
   private int diameter = 20;   // ball diameter

   private int velX = 2;         // velocity offset for x
   private int velY = 2;         // velocity offset for y

   public BallPanel()
   {
      timer = new Timer(delay, this);
      timer.start();        // start the timer
   }

   public void actionPerformed(ActionEvent e)  // This method runs when timer done
   {
    repaint();                // repaint panel to make ball in different place
   }

   public void paintComponent( Graphics g )    // determine ball position
   {
      super.paintComponent( g );    // call superclass's paintComponent 
      g.setColor(Color.black);      // set ball to black

       if (y > getHeight())        // make ball bounce off floor
       {
           velY = -velY;
       }
       x += velX;                  // add velocity offset for new position
       y += velY;                  // add velocity offset for new position
       g.fillOval(x, y, diameter, diameter);
   }

}

2 个答案:

答案 0 :(得分:0)

你只能发现球击中了地板。你还需要检查球是否已经撞到了天花板;

if (y < 0)        // make ball bounce off ceiling
   {
       velY = 2;
   }

同样,你需要检查它是否击中了左侧和右侧...

答案 1 :(得分:0)

您只检查Y坐标,并且仅检查是否低于0.

if(y <= 0 || y >= 300 || x <= 0 || x >= 600)

用if语句替换它,它应该可以工作。