Java中保持在边界内的弹跳球
我试图让这个弹跳球程序让球在窗口中弹跳,但无论我做什么,它都会弹跳一次,然后无限期地跳出屏幕。我该怎么做才能让它留在屏幕上Java中保持在边界内的弹跳球,java,swing,animation,graphics,Java,Swing,Animation,Graphics,我试图让这个弹跳球程序让球在窗口中弹跳,但无论我做什么,它都会弹跳一次,然后无限期地跳出屏幕。我该怎么做才能让它留在屏幕上 /* * 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.JPan
/*
* 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);
}
}
你只会发现球落在了地板上。你还需要检查球是否击中天花板
if (y < 0) // make ball bounce off ceiling
{
velY = 2;
}
if(y<0)//使球弹离天花板
{
fly=2;
}
同样,您需要检查它是否击中左侧和右侧…您只检查Y坐标,并且只有在低于0时才检查
if(y <= 0 || y >= 300 || x <= 0 || x >= 600)
if(y=300 | | x=600)
用if语句替换它,它应该可以工作。可能与or重复。请参阅以获取工作示例。不要检查或修改
paintComponent
中的状态,此方法可能会因不同的原因而被调用,而您不会启动,在actionPerformed
方法中更新它们如果你想要一些好的和复杂的东西,看看这个,跳出多个对象,如果一个球不够的话