上一节实现了满天星的效果,本节将实现滚雪球的小实例,这里要用到重绘和线程的知识,代码如下:
import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; public class SnowBall { public static void main(String[] args) { Frame frame=new Frame(); frame.setBackground(Color.BLACK); frame.setSize(1024, 768); MyPanel myPanel=new MyPanel(); frame.add(myPanel); Thread thread=new Thread(myPanel); thread.start(); frame.show(); } } class MyPanel extends Panel implements Runnable{ int x=120; int y=10; @Override public void paint(Graphics g) { g.setColor(Color.WHITE); g.fillOval(x, y, 20, 20); } @Override public void run() { while (true) { y++; if(y>768){ y=0; } repaint(); } } }
try { Thread.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }
原文:http://blog.csdn.net/yayun0516/article/details/50807756