Event handling in Java is based on the event-delegation model in which:
The way that this model works can be divide into the following two sub-tasks:
Before implementing these two sub-tasks, lets's look at the event hierachy.
Back to the top
Object getSource() - that returns the object that generated the event.
Subclasses of this class are as follows:
The AWTEvent class is divided into two types of events. These are Semantic Events and
Low-level Events.
Back to the top
The Event Hierarchy
The superclass of all events is java.util.EventObject. This class provides the method:
java.lang.Object
java.util.EventObject
java.awt.AWTEvent (Abstract class)
Semantic Events
These classes represent user interaction with a GUI component. For example, clicking a button,
selecting a menu item, scrolling, and changing text in a text filed or a text area.
Semantic event classes are:
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
ActionEvent
This class is generated by by an action that is performed by any of the following components:
AdjustmentEvent
This event is generated when adjustments are amde to an adjustable component such as a scrollbar. This class
provides the method int getValue(). It returns the current value designated by the adjustable component.
ItemEvent
This event is generated when an item is selected or deselected in an item selectable component.
These components are as follows:
TextEvent
This event is generated whenever the content of a text component is changed The subclasses for the the
TextComponent/JTextComponent class are:
Low-Level Events
These classes are used to represent low-level input or window operations. A single semantic
event can constitute several low-level events. For example, clicking a button is actually a sequence
of mouse movements followed by pressing and releasing a mouse button.
Low-level event classes are:
ContainerEvent
This event is generated when a component is added or removed from a container. Similar to the ComponentEvent class,
the events are handled internally by the AWT, and are normally not directly handled by the application.
FocusEvent
This event is generated when a component gains focus or loses focus. Gains focus means that the component can
recieve keystrokes. For instance, if a button gains focus, the visual appearance is a rectangle around its border;
a text field can have a blinking cursor. The method getId() inherited from AWTEvent can
be used to determine the state of the component. The class provides the following constants:
KeyEvent
The class KeyEvent is a subclass of InputEvent class. This event is generated when the user
presses or releases a key when typing characters.
The class provides the following constants:
The inherited method getId() returns the specific type of event denoted by one of the constants.
The class also provides the following methods:
MouseEvent
This class, like KeyEvent is a subclass of InputEvent class. This event is generated when the user
moves the mouse or presses the mouse button.The exact action is identified by the following constants:
In addition to the inherited method getId(), the class provides the following methods:
PaintEvent
This event is handled internally by AWT. It is generated when a component should have its
paint()/b> update() methods called.
WindowEvent
This event is generated when an operation is performed on a window. These operations are identified by the
following constants in the WindowEvent class. The exact action is identified by the following constants:
In addition to the inherited method getId(), the class provides the following method:
The Event Delegation Model
As was mentioned, the AWT events are represented by subclasses of the java.awt.AWTEvent class.
Note the following:
Event Type | Event Source | Listener Registration & Removal Methods provided by the source | Event Listener Listener Interface implemented by a Listener |
---|---|---|---|
ActionEvent |
|
|
ActionListener |
AdjustmentEvent | Scrollbar/JScrollbar |
|
AdjustmentListener |
ItemEvent |
|
|
ItemListener |
TextEvent |
|
|
TextListener |
Given the following interface: public interface constants { String button[] = {"Write", "Draw", "Paint", "Print"}, } import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; public class myJButton extends JButton implements constants { myJFrame f; JButton source; myJButton(myJFrame f) { this.f = f; } public void addButtons() { // 1. Get the contentPane for the frame myJFrame Container content = f.getContentPane(); // 2. Create an object of the class GridBaglayout GridBagLayout gbag = new GridBagLayout(); // 3. Set the layout manager for the container content.setLayout(gbag); // 4. Create an object of the class GridBagConstraints GridBagConstraints constraints = new GridBagConstraints(); // 5. Layout each component constraints.fill = GridBagConstraints.NONE; for (int i = 0; i < button.length; i++) { switch(i) { case 0: { source = new JButton(button[i]); constraints.gridx = 0; constraints.gridy = 1; constraints.weightx = 0.5; constraints.gridwidth = 1; constraints.gridheight = 1; break; } case 1: { // Set constraints break; } case 2: { source = new JButton(button[i], new ImageIcon("Firewks1.jpg")); // Set constraints break; } case 3: { source = new JButton(button[i]); // Set constraints } } gbag.setConstraints(b, constraints); content.add(b); // Register each button object source. addActionListener(new myActionListener(i)); } } }
Event Listener Interface | Event Listener Methods |
---|---|
ActionListener | actionPerformed( ActionEvent e) |
AdjustmentListener | adjustmentValueChanged( AdjustmentEvent e) |
ItemListener | itemStateChanged(ItemEvent e) |
TextListener | textVakueChanged( TextEvent e) |
// 3. ActionListener - Typical usage: import java.awt.event.ActionEvent; import java.awt.event.ActionListener; // Contains actionPerformed(...) public class myActionListener implements ActionListener, constants { int i; public myActionListener(int i) { this.i = i; } public void actionPerformed(ActionEvent e) { if (button[i].equals(e.getActionCommand())) System.out.println(button[i] + " was pressed"); } } Back to the top
Event Type | Event Source | Listener Registration & Removal Methods provided by the source | Event Listener Listener Interface implemented by a Listener |
---|---|---|---|
ComponentEvent | Component/JComponent |
|
ComponentListener |
ContainerEvent | Container |
|
ContainerListener |
FocusEvent | Component/JComponent |
|
FocusListener |
KeyEvent | Component/JComponent |
|
KeyListener |
MouseEvent | Component/JComponent |
|
MouseListener |
WindowEvent | Window |
|
WindowListener |
Event Listener Interface | Event Listener Methods |
---|---|
ComponentListener |
|
ContainerListener |
|
FocusListener |
|
KeyListener |
|
MouseListener |
|
MouseMotionListener |
|
WindowListener |
|
An event listener interface can contain more than one method. For example, the WindowListener interface has seven (7) methods. If such interface is implemented, then it is imperative that all the methods are coded, even though a source object might not be interested in all of the methods. The alternate way to handle this siutation is to provide empty body to those methods that are not of interest to the object. Luckly Java has provided these method in classes called Adapter classes. So, instead of implementing the interfaces you would extend the respective adapter class, and you would simply define the body for the method of interest.
myJFrame source = new myJFrame(frameTitle); source.addWindowListener(new myWindowEvents()); source.addKeyListener(new myKeyEvent()); WindowAdapter - Typical usage import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class myWindowEvents extends WindowAdapter implements constants { public void windowClosing(WindowEvent e) { // Flush any buffer // Close any opened file(s) // Do necessary clean up activity, then System.exit(0); } public void windowClosed(WindowEvent e) { System.out.println("windowClosed: " + e); } public void windowOpened(WindowEvent e) { // Do any necesary initialization tasks before any further activity System.out.println("windowOpened: " + e); } public void windowActivated(WindowEvent e) { System.out.println("windowActivated: " + e); } } KeyAdapter - typical usage import java.awt.event.KeyEvent; import java.awt.event.KeyAdapter; public class myKeyEvent extends KeyAdapter { myKeyEvent(){} public void keyTyped(KeyEvent e) // Handle the key typed event { displayInfo(e, "KEY TYPED: "); } public void keyPressed(KeyEvent e) // Handle the key pressed event { displayInfo(e, "KEY PRESSED: "); } public void keyReleased(KeyEvent e) // Handle the key released event { displayInfo(e, "KEY RELEASED: "); } private void displayInfo(KeyEvent e, String s) { String charString, keyCodeString; char ch = e.getKeyChar(); int keyCode = e.getKeyCode(); if (Character.isISOControl(ch)) charString = "key character = (an unprintable control character)"; else charString = "\n" + "key character = '" + ch + "'"; keyCodeString = "key code = " + keyCode + " (" + KeyEvent.getKeyText(keyCode) + ")"; System.out.print(s + " " + keyCodeString + charString + "\n"); } }