Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make a time delay in Java?

 
Avin Sinanan
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Condsider the situation.
1)I have a JFrame and this JFrame has a JButtton.
2)When ever I press this button it prints the "Hello There" by using the following -System.out.println("Hello There");
3)However when i press the button I do not want it to print it immediately. Lets say I wanted the program to wait 2 seconds then execute it.
How do I do this? Anyone have any ideas. Thanks in advance.All I could think of a for loop and let it count to a large number before executing the function. But that technique is not very accurate nore is it efficient.
Thanks for reading
 
Laudney Ren
Ranch Hand
Posts: 111
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the actionPerformed method of the actionListener, add:
sleep(10);
before the System.println("...");
This is a simple but usual way of delaying.
 
Jeremy Carter
Greenhorn
Posts: 4
Android Java Windows Vista
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm guessing this has changed since 2002.

Just posting in case someone finds this post through a search.

sleep(10); doesn't do anything for me.
Thread.sleep(2000); would sleep for 2 seconds in Java 1.6.

Regards

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic