当鼠标单击事件发生时,利用Math类的方法Random()产三个随机数,同时获得鼠标位置坐标,在鼠标单击处绘制圆,圆的颜色由三个随机数决定。
public class DrawRandonCircle extends Applet {
Color c;
int x;
int y;
public void init() {
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
this_mouseClked(e);
}
});
}
void this_mouseClked(MouseEvent e) {
x=e.getX();
y=e.getY();
//int rgb1=(int) (255*Math.random()); 也可以用这方法获得随机数
Random rd=new Random();
int rgb1=rd.nextInt(256);
int rgb2=rd.nextInt(256);
int rgb3=rd.nextInt(256);
c=new Color(rgb1, rgb2, rgb3);
repaint(); //擦掉原来的内容重新再画
}
public void paint(Graphics g) {
g.setColor(c);
g.fillOval(x, y, 20, 20);
}
//重载update方法,使每次点击鼠标所绘制的点圆得以保留
public void update(Graphics g) {
paint(g);
}
}
运行结果