Lesson Seventeen
Events and Event Listeners
In Lesson Eight, you learned how to use events to make your applets interactive. Now we're going to use inheritance and abstract classes to further the event handling process. This is where the EventObject, which is the parent to the AWTEvent comes into play. Below are some user actions and the event types associated with them:
User Action | Event Type |
Click a Button | ActionEvent |
Click a Component | MouseEvent |
Click an item in a Choice | ItemEvent |
Click an item in a Checkbox | ItemEvent |
Change text in a TextField | TextEvent |
Open a window | WindowEvent |
Iconify a window | WindowEvent |
Type a key | KeyEvent |
As you may have guessed, every xxxEvent requires an xxxListener, which has the return type void. Remembering that interfaces contain abstract methods, which are empty methods, in order to implement a listener, you must provide your own methods for all the methods that are part of the interface. Although you can leave the methods empty in your implementation. The following table shows the events, their listeners, and their handlers:
Event | Listener | Handlers |
ActionEvent | ActionListener | actionPerformed(ActionEvent) |
ItemEvent | ItemListener | itemStateChanged(ItemEvent) |
TextEvent | TextListener | textValueChanged(TextEvent) |
AdjustmentEvent | AdjustmentListener | adjustmentValueChanged(AdjustmentEvent) |
ContainerEvent | ContainerListener | componentAdded(ContainerEvent) |
| | componentRemoved(ContainerEvent) |
ComponentEvent | ComponentListener | componentMoved(ComponentEvent) |
| | componentHidden(ComponentEvent) |
| | componentResized(ComponentEvent) |
| | componentShown(ComponentEvent) |
FocusEvent | FocusListener | focusGained(FocusEvent) |
| | focusLost(FocusEvent) |
MouseEvent | MouseListener | mousePressed(MouseEvent) |
| | mouseReleased(MouseEvent) |
| | mouseEntered(MouseEvent) |
| | mouseExited(MouseEvent) |
| | mouseClicked(MouseEvent) |
| MouseMotionListener | mouseDragged(MouseEvent) |
| | mouseMoved(MouseEvent) |
KeyEvent | KeyListener | keyPressed(KeyEvent) |
| | keyTyped(KeyEvent) |
| | keyReleased(KeyEvent) |
WindowEvent | ComponentListener | windowMoved(WindowEvent) |
| | windowActivated(WindowEvent) |
| | windowClosing(WindowEvent) |
| | windowClosed(WindowEvent) |
| | windowDeiconified(WindowEvent) |
| | windowIconified(WindowEvent) |
| | windowOpened(WindowEvent) |
Question: Now that I know all the listeners, is this where I get to learn the hanlers and how to use them?
Answer: Yes. We're going to handle exceptions using try and catch.
Lesson Sixteen | Home | Lesson Eighteen
If you have a question about any of the lessons, feel free to ask.
|