如何在java中使用计时器和输入随机数?

时间:2012-03-21 10:59:42

标签: java random timer

任何人都可以教我如何在java中使用计时器,

例如:我希望我的椭圆在5秒后出现。以及如何设置随机坐标/宽度/高度,例如:

g.drawOval()< - 里面的数字应为random

1 个答案:

答案 0 :(得分:0)

你只需要创建包含随机化器生成的double值的变量。

double coordx=Math.random(); //this creates a random double value between 0 and 0.9999
double coordy=Math.random()*5;//between 0 and 4.9999
double width=(Math.random()+1)*5;//between 1 and 5.999

然后你写了一个像

这样的方法
public void drawIt(double coordx, double coordy, double width){
   Thread.sleep(1000); //time in miliseconds to wait before continuing
   g.drawOval(coordx,coordy,width); //i assume you already have drawOval and g
}

希望这对你有所帮助。

更简单的版本:

public void drawIt(){
double coordx=Math.random(); //this creates a random double value between 0 and 0.9999
double coordy=Math.random()*5;//between 0 and 4.9999
double width=(Math.random()+1)*5;//between 1 and 5.999
Thread.sleep(1000); //time in miliseconds to wait before continuing
g.drawOval(coordx,coordy,width); //i assume you already have drawOval and g
}