模拟一個小球碰壁後,沿光的反射方向運動的動畫。
package mypro01;
import java.awt.*;
class Main
{
public static void main(String[]args)
{
Frame f=new Frame();
f.setSize(1010,710);
MyPanel m=new MyPanel();
Thread t=new Thread(m);
t.start();
f.add(m);
f.show();
}
}
class MyPanel extends Panel implements Runnable
{
int y=0;
int x=0;
public void paint(Graphics g)
{
g.fillOval(x,y,40,40);
}
public void run()
{
boolean up=false;
boolean right=true;
while(true)
{
if(y>700||y<0)
{
if(up)
up=false;
else
up=true;
}
if(x<0||x>1000)
{
if(right)
right=false;
else
right=true;
}
if(right)
x++;
else
x--;
if(up)
y--;
else
y++;
try{
Thread.sleep(10);
}catch(Exception e){}
repaint();
}
}
}