AWT Event Model

As mentioned before, the AWT has its own event dispatch thread. This thread dispatches all sorts of events, such as mouse clicks and key presses coming in from the operating system. Where does the AWT dispatch these events? When an event occurs on a particular component, the AWT checks to see if there are any listeners for that event. A listener is an object that receives events from another object. In this case, events come from the AWT event dispatch thread. There is a different type of listener for every type of event. For example, for key input events, there is a KeyListener interface. Here's an example of how the event model works for a key press:

  1. The user presses a key.

  2. The operating system sends the key event to the Java runtime.

  3. The Java runtime posts the event to the AWT's event queue.

  4. The AWT event dispatch thread dispatches the event to any KeyListeners.

  5. The KeyListener receives the key event and does whatever it wants with it.

All listeners are interfaces, so any object can be a listener by implementing a listener interface. Also note that there can be several listeners for the same event type. For example, several objects could be listening for mouse events. This can be a useful feature, but you won't need to deal with multiple listeners for the same type of event in your code. There is a way to capture all AWT events. Although doing this isn't useful for a real game, it can be helpful for debugging your code or seeing what events get dispatched. The following code captures all the events by creating an AWTEventListener and prints the events to the console:

 new AWTEventListener() {
 public void eventDispatched(AWTEvent event) {
 }, -1);

Remember, don't use something like this in a real game; use it only for debugging.