0% found this document useful (0 votes)
11 views

Module 10 Gui Event Handling

Uploaded by

jacedump
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Module 10 Gui Event Handling

Uploaded by

jacedump
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Java Programming

Module 10

GUI Event Handling

What is the lesson all about?

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.

What do you expect from the lesson?

After completing this lesson, you should be able to:


 Explain the delegation event model components
 Understand how the delegation event model works
 Create GUI applications that interact with the user
 Discuss benefits of adapter classes
 Discuss advantages of using inner and anonymous classes

What are the contents of the lesson?

The Delegation Event Model


The Delegation event model describes how your program can respond to user interaction.
To understand the model, let us first study its three important components.

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.

Here now is the delegation event model.

Figure 1. Delegation Event Model

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.

void add<Type>Listener(<Type>Listener listenerObj)

<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.

A registered listener can also be unregistered using the remove<Type>Listener methods.

void remove<Type>Listener(<Type>Listener listenerObj)

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.

Event Class Description


ComponentEvent Extends AWTEvent. Instantiated when a component is moved,
resized, made visible or hidden.
InputEvent Extends ComponentEvent. The abstract root event class for all
component-level input event classes.
ActionEvent Extends AWTEvent. Instantiated when a button is pressed, a list item
is double-clicked, or a menu item is selected.
ItemEvent Extends AWTEvent. Instantiated when an item is selected or
deselected by the user, such as in a list or a checkbox.
KeyEvent Extends InputEvent. Instantiated when a key is pressed, released or
typed.
MouseEvent Extends InputEvent. Instantiated when a mouse button is pressed,
released, or clicked (pressed and released), or when a mouse cursor
enteres or exits a visible part of a component.
Java Programming

Event Class Description


TextEvent Extends AWTEvent. Instantiated when the value of a text field or a
text area is changed.
WindowEvent Extends ComponentEvent. Instantiated when a Window object is
opened, closed, activated, deactivated, iconified, deiconified, or when
focus is transferred into or out of the window.

Table 1. 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.

Event Listeners Description


ActionListener Receives action events.
MouseListener Receives mouse events.
MouseMotionListener Receives mouse motion events, which include dragging and
moving the mouse.
WindowListener Receives window events.

Table 2. Event Listeners

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.

Table 3. The ActionListener method


Java Programming

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.

Table 3. The MouseListener methods

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.

Table 4. The MouseMotionListener methods

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.

Table 5. The WindowListener methods

Guidelines for Creating Applications Handling GUI Events

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.

Mouse Events Example

import java.awt.*;
import java.awt.event.*;

public class MouseEventsDemo extends Frame implements


MouseListener, MouseMotionListener
{
TextField tf;
public MouseEventsDemo(String title){
Java Programming

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

Figure 1. Output of MouseEventsDemo program

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame implements WindowListener {


Label label;

CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(this);
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

public void windowActivated(WindowEvent e) {


}
public void windowClosed(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
Java Programming

public void windowIconified(WindowEvent e) {


}
public void windowOpened(WindowEvent e) {
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Figure 2. Output of CloseFrame program

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.

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;
CFListener w = new CFListener(this);

CloseFrame(String title) {
super(title);
Java Programming

label = new Label("Close the frame.");


this.addWindowListener(w);
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

class CFListener extends WindowAdapter{


CloseFrame ref;
CFListener( CloseFrame ref ){
this.ref = ref;
}

public void windowClosing(WindowEvent e) {


ref.dispose();
System.exit(1);
}
}

Figure 3. Output of CloseFrame program


Java Programming

Inner Classes and Anonymous Inner Classes

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.

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;

CloseFrame(String title) {
super(title);
label = new Label("Close the frame.");
this.addWindowListener(new CFListener());
}

void launchFrame() {
setSize(300,300);
setVisible(true);
}

class CFListener extends WindowAdapter {


public void windowClosing(WindowEvent e) {
dispose();
System.exit(1);
}
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Anonymous Inner Classes

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

Close Window Example

import java.awt.*;
import java.awt.event.*;

class CloseFrame extends Frame{


Label label;

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);
}

public static void main(String args[]) {


CloseFrame cf = new CloseFrame("Close Window Example");
cf.launchFrame();
}
}

Option Dialog Example

import javax.swing.*;

public class OptionsDialogTest{

public static void main(String[] args) {

JTextField name = new JTextField();


JTextField initials = new JTextField(6);
JTextField age = new JTextField(3);
JTextArea interests = new JTextArea(10,10);
interests.setLineWrap(true);
interests.setWrapStyleWord(true);

JScrollPane jsp = new JScrollPane(


interests,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );

String s0 = "Please enter your last name";


String s1 = "Please enter your initials";
Java Programming

String s2 = "Please enter your age\n(in years)";


String s3 = "Please enter your main interests\n(maximum 500 words)";

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.out.println("name = " + name.getText());


System.out.println("initials = " + initials.getText());
System.out.println("age = " + age.getText());
System.out.println("interests = " + interests.getText());

System.exit(0);

}
}

Figure 4. Output of OptionDialog program


Java Programming

Name: _________________________________________________________________
Year & Section:___________________________ Date ___________________________

SKILLS WARM-UP

True or False. Write your answer in the space provided.

_______ 1. The method addWindowListener is included in the class Frame.

_______ 2. When you click a JButton, an event, known as an action event, is created.

_______ 3. The class ActionListener contains only one method, actionPerformed.

_______ 4. An action event is handled by the class JFrame.

_______ 5. An object that is interested in an event is called a source.


Java Programming

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.

Figure 1.6.1: The Tic-Tac-Toe program

You might also like