Event Handling

An event is an object that’s generated when the user does something noteworthy with one of your user interface components. Then this event object is passed to a special method you create, called an event listener. The event listener can examine the event object, determine exactly what type of event occurred, and respond accordingly. If the user clicks a button, the event listener might write any data entered by the user via text fields to a file. If the user passes the mouse over a label, the event handler might change the text displayed by the label. And if the user selects an item from a combo box, the event handler might use the value that was selected to look up information in a database.

Java provides several types of event objects, represented by various classes that all inherit AWTEvent. The most commonly used event objects are ActionEvent and ItemEvent. Both of these event objects are described in separate entries in this part.

Each event object has a corresponding listener interface that you use to create an object that can listen for the event and handle it when it is generated. The most common listener interfaces are ActionListener and ItemListener. Both of these interfaces are covered in separate entries in this part.

To write Java code that responds to events, you have to do the following:

1. Create a component that can generate events.

Add buttons or other components that generate events to your frame so that it displays components the user can interact ...

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.