import java.awt.*;
import java.awt.event.*;
class objectMovement
{
public static void main(String[] args)
{
Movement move=new Movement();
move.setBounds(10,10,450,450);
move.setVisible(true);
move.setTitle("模仿自由落体和平抛运动");
move.addWindowListener(new WindowAdapter(){public void WindowClosing(WindowEvent e){System.exit(0);}});
//System.out.println("Hello World!");
}
}
class Movement extends Frame implements Runnable
{
Thread RedBall,BlueBall;
Ball red,blue;
double t=0;
Movement()
{
RedBall=new Thread(this);
red=new Ball(Color.red);
BlueBall=new Thread(this);
blue=new Ball(Color.blue);
setLayout(null);
add(red);
add(blue);
red.setLocation(50,100);
blue.setLocation(80,100);
RedBall.start();
BlueBall.start();
}
public void run()
{
while (true)
{
t=t+0.2;
if(t>20) t=0;
if (Thread.currentThread()==RedBall)
{
int x=50;
int y=(int)(1.0/2*t*t*3.8)+50;
red.setLocation(x,y);
try
{
Thread.sleep(45);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (Thread.currentThread()==BlueBall)
{
int x=50+(int)(26*t);
int y=(int)(1.0/2*t*t*3.8)+50;
red.setLocation(x,y);
try
{
Thread.sleep(45);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class Ball extends Canvas
{
Color color;
Ball (Color color)
{
setSize(20,20);
this.color=color;
}
public void paint(Graphics g)
{
g.setColor(color);
g.fillOval(0,0,20,20);
}
}
以上是一个模仿自由落体运动的小实验。
运行结果:
|
|