Event-Handling Basics


Introduction

In the previous chapter we created a rather complex interface (MainFrame). In this chapter, we’ll discuss how to handle GUI events and we’ll customize MainFrame’s response to user input. MainFrame’s interface is already interactive, thanks to the default behavior of the AWT and Swing components. For instance, clicking on a menu causes menu items to appear; clicking on radio buttons and checkboxes toggles them appropriately; and text areas display typed characters. But if that were all they did, our application would still be virtually useless.

To customize our application’s behavior further, we need:

  • A way of capturing an event we’re interested in (e.g. typing on the keyboard or clicking with the mouse) whenever it happens on the component we’re interested in

  • A way to find out the particulars of the event (e.g. what key was typed or which button was clicked) so that we know exactly what happened

  • A way of telling the application what piece of code (that we will write) to execute and under which conditions to execute it

Fortunately for us, Sun Microsystems has provided an event-handling framework that provides all this. Behind the scenes, when an event occurs, the framework figures out which component the event initially occurred on and sends the event to that component. The component then searches through a list of registered event listeners for any it may contain that were listening for that kind of event. It notifies each listener, which is then free to query the event and to respond however it has been coded to respond.

Handling a GUI event using the event-handling framework requires the programmer to accomplish three tasks:

  • Choose the event and component of interest

  • Implement the appropriate event listener, giving it the desired application behavior

  • Register the listener with the component of interest

If the programmer does this, then any occurrence of that event type on that component will cause the execution of whatever code was written into the listener.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net