Results 1 to 8 of 8
Thread: Press key to exit loop
- 06-14-2012, 05:26 AM #1
Member
- Join Date
- Jun 2012
- Posts
- 12
- Rep Power
- 0
Press key to exit loop
In my program, I am constantly performing the same task, as many times per second as possible. The thing is, I want to be able to exit the loop at will. I think the best way is to have it make the user press the "Q" key to end the program. How do I set this up? I know I need to use break and keyevent. But I'm not sure how to implement it.
- 06-14-2012, 07:21 AM #2
Re: Press key to exit loop
Unanswerable without more detail.
If this is a console program, it can't be done. Not with a single keypress anyways.
If this is a GUI program you need to tell us what GUI toolkit is used.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 06-14-2012, 03:08 PM #3
Member
- Join Date
- Jun 2012
- Posts
- 12
- Rep Power
- 0
Re: Press key to exit loop
I'm using AWT and Swing. I think that answers your question.
- 06-14-2012, 04:42 PM #4
Member
- Join Date
- Apr 2012
- Posts
- 59
- Rep Power
- 0
Re: Press key to exit loop
Then your best bet is to put the executing code into a thread (a Runnable class or Thread class), make it check some variable for quit condition (i.e. boolean isTimeToQuit) then stick a KeyListener (How to Write a Key Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)) on your window to catch the 'Q' press and change isTimeToQuit to true.
- 06-14-2012, 05:46 PM #5
Member
- Join Date
- Jun 2012
- Posts
- 12
- Rep Power
- 0
Re: Press key to exit loop
I don't know what that means. Runnable class? Thread class? And I don't know how the KeyListener is implemented. Can I get more detail?
- 06-14-2012, 05:53 PM #6
Member
- Join Date
- Apr 2012
- Posts
- 59
- Rep Power
- 0
Re: Press key to exit loop
I left a link for the KeyListener, as for the Thread and Runnable they are two ways to split your program into two threads and make it do more than one thing simultaneously, it's easy to find info on them online. Just look up multi-threaded programming in Java
-
Re: Press key to exit loop
- 06-14-2012, 08:10 PM #8
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,399
- Blog Entries
- 7
- Rep Power
- 17
Similar Threads
-
Press any key to continue
By romero4742 in forum New To JavaReplies: 3Last Post: 05-23-2012, 04:20 AM -
Using a while loop and using a string variable to exit the program
By Beaner462 in forum New To JavaReplies: 10Last Post: 05-11-2011, 02:26 AM -
Can't seem to understand why my while loop doesn't exit!
By Vortexnl in forum New To JavaReplies: 5Last Post: 02-11-2011, 08:33 PM -
How to exit the program by typing "exit"?
By Laythe in forum New To JavaReplies: 6Last Post: 08-19-2009, 08:32 PM -
Press any key to continue/press enter
By JT4NK3D in forum New To JavaReplies: 1Last Post: 11-17-2007, 09:27 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks