When you run Java GUI programs, the program interacts with the user and the events drive its execution. An event can be defined as a signal to the program that something has happened . Events are triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by internal program activities, such as a timer. The program can choose to respond to or ignore an event.
The component on which an event is fired or generated is called the source object or source component . For example, a button is the source object for a button-clicking action event. An event is an instance of an event class. The root class of the event classes is java.util.EventObject . The hierarchical relationships of some event classes are shown in Figure 14.2.
An event object contains whatever properties are pertinent to the event. You can identify the source object of an event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as action events, window events, component events, mouse events, and key events. Table 14.1 lists external user actions, source objects, and event types fired.
User Action | Source Object | Event Type Fired |
---|---|---|
Click a button | JButton | ActionEvent |
Press return on a text field | JTextField | ActionEvent |
Select a new item | JComboBox | ItemEvent , ActionEvent |
Select item(s) | JList | ListSelectionEvent |
Click a check box | JCheckBox | ItemEvent , ActionEvent |
Click a radio button | JRadioButton | ItemEvent , ActionEvent |
Select a menu item | JMenuItem | ActionEvent |
Move the scroll bar | JScrollBar | AdjustmentEvent |
Window opened, closed, iconified , deiconified, or closing | Window | WindowEvent |
Mouse pressed, released, clicked, entered, or exited | Component | MouseEvent |
Mouse moved or dragged | Component | MouseEvent |
Key released or pressed | Component | KeyEvent |
Component added or removed from the container | Container | ContainerEvent |
Component moved, resized, hidden, or shown | Component | ComponentEvent |
Component gained or lost focus | Component | FocusEvent |
Note
If a component can fire an event, any subclass of the component can fire the same type of event. For example, every GUI component can fire MouseEvent , KeyEvent , FocusEvent , and ComponentEvent , since Component is the superclass of all GUI components . |
Note
All the event classes in Figure 14.2 are included in the java.awt.event package except ListSelectionEvent , which is in the javax.swing.event package. AWT events were originally designed for AWT components, but many Swing components fire them.