I have been working on a school assignment and it is functioning perfectly. However, I want to refine it a bit and one of the areas that I want to do this is where I am pausing the loop. I am currently using the Thread.sleep class to do it but I would rather the user hit a key to continue the loop instead.
Here is the area that I am speaking of...
Is there something that I can use that will wait until the user hits key instead of waiting 2.5 seconds? If anyone has a tip or can point me towards something that might help, I would appreciate it.
First thing you would need to do is put that code into its own thread so it doesn't block the GUi.
Then you would need to have a synchronized block in that code.
You would also have a synchronized block in your button's actionPerformed method
If you aren't familiar with Threading you can google Java concurrency and find a lot of information including a Sun tutorial page which covers all you would need for this purpose. Careful with playing with threads though, you can get plenty of weird behavior if you do it wrong. So you should read sun's tutorial on swing and concurrency as well.
Christophe Verré wrote:Is this a Swing application ?
Crikey! Why did I read 'button' when he wrote 'key'?
The answer could be rather different if you aren't using Swing, and are using command line instead.
Joined: Jun 03, 2006
Sorry guys, I am using CLI on this not Swing, I should have specified. It is no biggie and can be turned in as is for a full grade, I just want to know for my own understanding. Google didn't show much.
Will Potere wrote:Sorry guys, I am using CLI on this not Swing, I should have specified. It is no biggie and can be turned in as is for a full grade, I just want to know for my own understanding. Google didn't show much.
Sorry. If you wanted to do this on the command line the simplest approach is to use an inner loop that tells the user to press a specific button to continue:
"Enter P to unpause"
You read system in and check for the entered character. If it matches "P" then continue. If not, re-prompt. This works because the program halts (blocks) when waiting for user input. If the user doesn't put anything in, the program must sit still until the user does.
[haha. I tried to use the letter ewe (sound it out) instead of p, but the forum won't let me :-)]
Joined: Jun 03, 2006
Steve, thanks for that. I'll give it a go and see if I can make it work.