java 基础三 下雪

通过repaint()方法进行重画。

 1 import javax.swing.JFrame;
 2 import javax.swing.JPanel;
 3 import java.awt.Graphics;
 4 
 5 public class Demo05{
 6 
 7     public static void main(String[] args){
 8     
 9         JFrame f = new JFrame();//创建一个窗体
10         f.setSize(500,500);//设计窗体大小
11         f.setLocationRelativeTo(null);//窗体居中
12         f.setVisible(true);//窗体可见 该方法默认为不可见f.setVisible(false);
13         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗体程序结束
14         MyPanel p = new MyPanel();//创建面板类
15         f.add(p);//将面板添加到窗体里
16     }        
17 }
18 class MyPanel extends JPanel{
19     int[] x = new int[50];
20     int[] y = new int[50];
21     MyPanel(){
22         for(int i = 0 ;i<50;i++)
23         {
24             x[i] = (int)(Math.random()*500);
25             y[i] = (int)(Math.random()*500);
26         }
27     }
28     public void paint(Graphics g){
29         super.paint(g);
30         for(int i = 0;i<50;i++)
31         {    
32             g.drawString("*",x[i],y[i]);
33         }
34         for(int i = 0;i<50;i++)
35         {
36             y[i]++;
37             if(y[i]==500)
38              {
39                             y[i]=0;
40                          }
41         }
42         try{
43             Thread.sleep(10);
44         }catch(Exception e){}
45         repaint();
46     }
47 }

 

posted on 2016-12-25 15:01  化身孤岛的蓝鲸  阅读(408)  评论(0)    收藏  举报

导航