Module 10 Gui Event Handling
Module 10 Gui Event Handling
Module 10
In this lesson, you will learn how to handle events triggered when the user interacts with
your Graphical User Interface application. After completing this module, you'll be able to
develop GUI applications that responds to user interaction.
1. Event Source
The event source refers to the GUI component that generates the event. For example, if
the user presses a button, the event source in this case is the button.
Java Programming
2. Event Listener/Handler
The event listener receives news of events and processes user's interaction. When a
button is pressed, the listener may handle this by displaying an information useful to the
user.
3. Event Object
When an event occurs (i.e., when the user interacts with a GUI component), an event
object is created. The object contains all the necessary information about the event that
has occurred. The information includes the type of event that has occurred, say, the
mouse was clicked. There are several event classes for the different categories of user
action. An event object has a data type of one of these classes.
Initially, a listener should be registered with a source so that it can receive information about
events that occur at the source. Only registered listeners can receive notifications of events.
Once registered, a listener simply waits until an event occurs.
When something happens at the event source, an event object describing the event is
created. The event is then fired by the source to the registered listeners.
Java Programming
Once the listener receives an event object (i.e., a notification) from the source, it goes to
work. It deciphers the notification and processes the event that occurred.
Registration of Listeners
The event source registers a listener through the add<Type>Listener methods.
<Type> depends on the type of event source. It can be Key, Mouse, Focus, Component,
Action and others.
Several listeners can register with one event source to receive event notifications.
Event Classes
An event object has an event class as its reference data type. At the root of event class
heirarchy is the EventObject class, which is found in the java.util package. An immediate
subclass of the EventObject class is the AWTEvent class. The AWTEvent class is defined in
java.awt package. It is the root of all AWT-based events. Here are some of the AWT event
classes.
Take note that all AWTEvent subclasses follow this naming convention:
<Type>Event
Event Listeners
Event listeners are just classes that implement the <Type>Listener interfaces. The following
table shows some of the listener interfaces commonly used.
ActionListener Method
The ActionListener interface contains only one method.
ActionListener Method
public void actionPerformed(ActionEvent e)
Contains the handler for the ActionEvent e that occurred.
MouseListener Methods
These are the MouseListener methods that should be overriden by the implementing class.
MouseListener Methods
public void mouseClicked(MouseEvent e)
Contains the handler for the event when the mouse is clicked (i.e., pressed and
released).
public void mouseEntered(MouseEvent e)
Contains the code for handling the case wherein the mouse enters a component.
public void mouseExited(MouseEvent e)
Contains the code for handling the case wherein the mouse exits a component.
public void mousePressed(MouseEvent e)
Invoked when the mouse button is pressed on a component.
public void mouseReleased(MouseEvent e)
Invoked when the mouse button is released on a component.
MouseMotionListener Methods
The MouseMotionListener has two methods to be implemented.
MouseListener Methods
public void mouseDragged(MouseEvent e)
Contains the code for handling the case wherein the mouse button is pressed on a
component and dragged. Called several times as the mouse is dragged.
public void mouseMoved(MouseEvent e)
Contains the code for handling the case wherein the mouse cursor is moved onto a
component, without the mouse button being pressed. Called multiple times as the
mouse is moved.
WindowListener Methods
These are the methods of the WindowListener interface.
WindowListener Methods
public void windowOpened(WindowEvent e)
Contains the code for handling the case when the Window object is opened (i.e., made
visible for the first time).
Java Programming
WindowListener Methods
public void windowClosing(WindowEvent e)
Contains the code for handling the case when the user attempts to close Window object
from the object's system menu.
public void windowClosed(WindowEvent e)
Contains the code for handling the case when the Window object was closed after
calling dispose (i.e., release of resources used by the source) on the object.
public void windowActivated(WindowEvent e)
Invoked when a Window object is the active window (i.e., the window in use).
public void windowDeactivated(WindowEvent e)
Invoked when a Window object is no longer the active window.
public void windowIconified(WindowEvent e)
Called when a Window object is minimized.
public void windowDeiconified(WindowEvent e)
Called when a Window object reverts from a minimized to a normal state.
These are the steps you need to remember when creating a GUI application with event
handling.
1. Create a class that describes and displays the appearance of your GUI application.
2. Create a class that implements the appropriate listener interface. This class may refer to
the same class as in the first step.
3. In the implementing class, override ALL methods of the appropriate listener interface.
Describe in each method how you would like the event to be handled. You may give
empty implementations for methods you don't want to handle.
4. Register the listener object, the instantiation of the listener class in step 2, with the
source component using the add<Type>Listener method.
import java.awt.*;
import java.awt.event.*;
super(title);
tf = new TextField(60);
addMouseListener(this);
}
public void launchFrame() {
/* Add components to the frame */
add(tf, BorderLayout.SOUTH);
setSize(300,300);
setVisible(true);
}
public void mouseClicked(MouseEvent me) {
String msg = "Mouse clicked.";
tf.setText(msg);
}
public void mouseEntered(MouseEvent me) {
String msg = "Mouse entered component.";
tf.setText(msg);
}
public void mouseExited(MouseEvent me) {
String msg = "Mouse exited component.";
tf.setText(msg);
}
public void mousePressed(MouseEvent me) {
String msg = "Mouse pressed.";
tf.setText(msg);
}
public void mouseReleased(MouseEvent me) {
String msg = "Mouse released.";
tf.setText(msg);
}
public void mouseDragged(MouseEvent me) {
String msg = "Mouse dragged at " + me.getX() + "," + me.getY();
tf.setText(msg);
}
public void mouseMoved(MouseEvent me) {
String msg = "Mouse moved at " + me.getX() + "," + me.getY();
tf.setText(msg);
}
public static void main(String args[]) {
MouseEventsDemo med = new MouseEventsDemo("Mouse Events Demo");
med.launchFrame();
}
}
Java Programming
import java.awt.*;
import java.awt.event.*;
CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(this);
}
void launchFrame() {
setSize(300,300);
setVisible(true);
}
Adapter Classes
Implementing all methods of an interface takes a lot of work. More often than not, you are
interested in implementing some methods of the interface only. Fortunately, Java provides
us with adapter classes that implement all methods of each listener interface with more
than one method. The implementations of the methods are all empty.
import java.awt.*;
import java.awt.event.*;
CloseFrame(String title) {
super(title);
Java Programming
void launchFrame() {
setSize(300,300);
setVisible(true);
}
This section gives you a review of a concept you've already learned in your first
programming course. Inner classes and anonymous inner classes are very useful in GUI event
handling.
Inner Classes
Here is a brief refresher on inner classes. An inner class, as its name implies, is a class
declared within another class. The use of inner classes would help you simplify your
programs, especially in event handling as shown in the succeeding example.
import java.awt.*;
import java.awt.event.*;
CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(new CFListener());
}
void launchFrame() {
setSize(300,300);
setVisible(true);
}
Now, anonymous inner classes are unnamed inner classes. Use of anonymous inner classes
would further simplify your codes. Here is a modification of the example in the preceding
section.
Java Programming
import java.awt.*;
import java.awt.event.*;
CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
dispose();
System.exit(1);
}
});
}
void launchFrame() {
setSize(300,300);
setVisible(true);
}
import javax.swing.*;
JOptionPane.showOptionDialog(
null,
new Object[] {s0,name,s1,initials,s2,age,s3,jsp},
"Personal Info",
JOptionPane.OK_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
null,
null
);
System.exit(0);
}
}
Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________
SKILLS WARM-UP
_______ 2. When you click a JButton, an event, known as an action event, is created.
Hands-on Activity
Tic-Tac-Toe
Extend the Tic-Tac-Toe board program you've previously developed and add event
handlers to the code to make your program fully functional. The game of Tic-Tac-Toe is a
two-player game. The players alternate taking turns. For each turn, a player gets to
select a square from the board. Once a square is selected, the square is marked by the
player's symbol (O and X are usually used as symbols). The player who successfully
conquers 3 squares forming a horizontal, vertical or diagonal line wins the game. The
game ends when a player wins or when all squares have already been taken.