-3

can anyone teach me how to use a timer in java,

for example: i want my oval to appear after 5 seconds. and how to put random coordinates/width/height, for example:

g.drawOval()<-- numbers inside should be random.

mgraph
  • 15,238
  • 4
  • 41
  • 75

1 Answers1

0

you just need to create variables containing double values generated with a randomizer.

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

then you write a method like

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
}

hope this helped you.

even easier version:

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
}
Wandang
  • 912
  • 2
  • 8
  • 37
  • problem, only one shape is appearing, i wanted for the shapes to appear at the same time every 2 seconds. and how can i put the Thread.sleep(1000); here i was having an error. (cant post my code T_T need to wait for 8hrs) – Andy Velasquez Mar 21 '12 at 13:42
  • public void paint(Graphics 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 h2 = rand.nextInt(50); int R = (int) (Math.random( )*256); int G = (int)(Math.random( )*256); int B= (int)(Math.random( )*256); Color randomColor = new Color(R, G, B); g.setColor(randomColor); g.fillOval(x,y,w,h); g.fillRect(x,y,w,h); g.fillRoundRect(x,y,w,h,w2,h2); Thread.sleep(1000); } – Andy Velasquez Mar 21 '12 at 13:43
  • glad you found a solution yourself :) – Wandang Mar 21 '12 at 15:15