本帖最后由 谭立文 于 2012-10-7 15:13 编辑
package com.wenfengkeji.heima;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Demo13 extends Frame{
public static void main(String[] args) {
new DrawFrame();
}
}
class DrawFrame extends Frame{
static ArrayList points = null;
Image offScreenImage = null;
DrawFrame(){
points = new ArrayList();
setBounds(200,200,500,500);
setLayout(new FlowLayout());
Button reDraw = new Button("重画");
add(reDraw);
this.setVisible(true); //哥们这句你好像掉了
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
reDraw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
boolean flag = true;
int x,y;
while(flag){
x = new Random().nextInt(500);
y = new Random().nextInt(500);
points.add(new Point(x,y));
repaint();
if(points.size()>5000) //当随机生成圆心的坐标 的个数大于5000时循环结束
flag = false;
}
}
});
}
//看着有点闪屏幕 给你加了一个缓冲
@Override
public void update(Graphics g) {
if(offScreenImage == null) {
offScreenImage = this.createImage(500, 500);
}
Graphics gOffScreen = offScreenImage.getGraphics();
Color c = gOffScreen.getColor();
gOffScreen.setColor(Color.GREEN);
gOffScreen.fillRect(0, 0, 500, 500);
gOffScreen.setColor(c);
paint(gOffScreen);
g.drawImage(offScreenImage, 0, 0, null);
}
public void paint(Graphics g){
int red,green,blue;
Iterator i = points.iterator();
while(i.hasNext()){ //对集合进行迭代
Point point = (Point)i.next(); //迭代出来的是一个Point类实例 如果用泛型就更好了 不需要强转了
red = new Random().nextInt(255); //随机生成RGB对应的值
green = new Random().nextInt(255);
blue = new Random().nextInt(255);
g.setColor(new Color(red,green,blue)); //根据随机生成的RGB值确定当前画笔的颜色
g.fillOval(point.x, point.y, 15,15); //这里的 point.x和point.y是同时从ArrayList中取出来,同时画 ? //取出来的是Point类的实例 该实例是对二维点坐标的描述
//根据当前被迭代出来Point的坐标 在画布上画出圆心 其实是以点为(point.x point.y)圆心 正方形 为15的内切圆
}
}
} |