Loop not accept my key entry - Java AWT

advertisements

I am using a while loop in my method

public void keyTyped (KeyEvent e)

The problem here is that, the program enters the loop, it asks the user for input. And if the input is within the parameters, set by "while", it just keeps on repeating that input infinitely. It doesn't ask for another input again though I did put in the code for it to do so.

What I need is for it to ask the user for input each time it loops. Any help?

//cardChosen1 is "null" at this point`
            while (cardChosen1 < 97  || cardChosen1 > 108)
            {

                Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
                cardChosen1 = e.getKeyChar ();
                System.out.println ("Inside Loop" + cardChosen1);

                repaint ();
                try
                {
                    // Stop thread for 20 milliseconds
                    Thread.sleep (20);
                }
                catch (InterruptedException ex)
                {
                    // do nothing
                }
                Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);
            }


AWT, like most GUI frameworks, is event driven. That is, you register some kind of callback/observer/listener with the API and wait for that callback/observer/listener to be notified that something has happened.

You have to remember that a GUI is not a linear progress of code, but instead, events can occur at any time in any sequence and you need to code for those occurrences.

Start by taking a look at Event Dispatching Thread to understand the core mechanism by which events are generated and notification is made within an AWT based framework.

Then take a look at How to write KeyListeners to find out how you get notified of key events within your program.

Without more details about what you are trying to achieve, it's difficult to provide more information, but essentially, NEVER block the EDT, this will prevent it from process new events in the event queue and make it look like your program has hung (because it essentially has)