天天看点

java小程序(小球碰壁)

模拟一个小球碰壁后,沿光的反射方向运动的动画。

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();
				}
				
		
	}
}