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

如何在java中使用计时器和输入随机数?,java,random,timer,Java,Random,Timer,有人能教我如何用java来使用计时器吗 例如:我希望我的椭圆在5秒后出现。以及如何放置随机坐标/宽度/高度,例如: g.drawOval()您只需要创建包含随机数发生器生成的双值的变量 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=(Mat

有人能教我如何用java来使用计时器吗

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


g.drawOval()
您只需要创建包含随机数发生器生成的双值的变量

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
}

问题,只有一个形状出现,我希望形状每2秒同时出现。我怎样才能把线放进去。睡眠(1000);这里我有一个错误。(无法发布我的代码,不需要等待8小时)公共无效绘制(图形g){Random rand=new Random();int x=rand.nextInt(750);int y=rand.nextInt(750);int w=rand.nextInt(750);int h=rand.nextInt(750);int w2=rand.nextInt(50);int R=(int)(Math.Random()*256);int g=(int)(Math.Random()*256);intb=(int)(Math.random()*256);Color randomColor=新颜色(R,G,B);G.setColor(randomColor);G.fillOval(x,y,w,h);G.fillRect(x,y,w,h,w2,h2);Thread.sleep(1000);}很高兴您自己找到了一个解决方案:)可能的重复