上一節實現了滿天星的效果,本節將實現滾雪球的小實例,這裡要用到重繪和線程的知識,代碼如下:
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(); }