Java Notes

Events -- Introduction

Events from User Interface Controls

When a user performs an action on the user interface, eg clicks on a button, it's necessary for the button (the publisher) to call on code (the subscriber or listener) to perform the appropriate actions. This is done in Java GUI programming by adding one or more listeners to each GUI control. The listeners are called whenever an event is created by a GUI control.

Every Input Control (JButton, JSlider, ...) needs an event listener

If you want a control to do something when the user alters the control, you must have a listener.

Types of Events

There are several kinds of events. The most common in beginning programming is an ActionEvent, and this is the only one you will need for your first GUI interfaces.

User Control addXXXListener method in listener
JButton
JTextField
JMenuItem
addActionListener() actionPerformed(ActionEvent e)
JSlider addChangeListener() stateChanged(ChangeEvent e)
JCheckBox addItemListener() itemstateChanged()
keyboard addKeyListener() keyPressed(), keyReleased(), keyTyped()
mouse addMouseListener() mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), mouseReleased()
mouse addMouseMotionListener() mouseMoved(), mouseDragged()
JFrame addWindowListener() windowClosing(WindowEvent e), ...

import Statements

To use events, you must have these import statements:

import java.awt.*
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

Patterns

The overall programming technique of registering listeners to be notified when something changes is called the Publisher-Subscriber or Observer pattern. It is the most common technique for connecting a GUI to the logic code and you will find it in all GUI oriented programming languages.

References