I am relatively new to Java, so please excuse me if I'm not specific enough. I am making a program where a large portion of it is just one big while loop, and I want to be able to read specific keys being pushed to invoke different commands and methods, but apparently KeyListener doesn't work inside of a loop. Is there another, relatively simple way for me to read keyboard input?
If you're using Swing you have to 'invert' your logic, i.e. your program is not in
control as long as the user doesn't do anything. Your program doesn't wait or
run in a while loop. It's one special thread the EDT (Event Dispatch Thread) that
does the waiting (and painting of visual components if needed) and fires an
event to a registered Listener when the user causes that event.
Basically you register your KeyListener to some component and don't do anything
at all. When the user presses a key the EDT fires an event and your Listener will
be activated. Only then does your program do something: it should quickly do
something as long as it runs in the EDT or start another thread that does the job.
A lot of people make that mistake: they process whatever they have to process
in the EDT which ties that thread to your business logic; it is supposed to check
for events and repaint visual components instead. As long as its busy for your
purposes it can't pay any attention to user gestures and your application seems
to respond sluggish.
kind regards,
Jos