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

Lecture 20 Event Handling

Uploaded by

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

Lecture 20 Event Handling

Uploaded by

Abcd Efgh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Maharaja Agrasen Institute of Technology

CIC-212 Java Programming

Event Handling
Delegation Event Model
Concept
:• A source generates an event and sends it to one or more
listeners.
• Listener simply waits until it receives an event.
• Once an event is received, the listener processes the event and
returns.
• Listener must register with a source in order to receive an event
notification.
Event: An event is an object that describes change in state in a
source.
As a result of person interacting with GUI: pressing button, clicking
mouse, entering character from KB
w/o person interaction : timer expires, counter exceeds some value
Event Listeners
 When the user performs an action, Java creates an
object containing information about the event.
 Responding to an event is done by writing a method
that can be called when the event occurs.
 Steps involved in handling an event:
1. The user performs an action, causing an event to be triggered
(or fired).
2. An object is created that contains information about the event,
including an indication of which component was involved.
3. A method that belongs to a listener object is called. The object
created in step 2 is passed to the method.
Events
 When an event occurs, an object is created that
contains information about the event.
 This object will belong to one of several different
classes, depending on the nature of the event.
 All these classes belong to the
java.awt.event package.
 Java divides events into two groups: “high-level”
events and “low-level” events.
Events
High-level Events:
Class Name Description of Event
ActionEvent A significant action has been performed on
a component (a button was pressed, a list
item was double-clicked, or the Enter key
was pressed in a text field).

AdjustmentEvent The state of an adjustable component (such


as a scrollbar) has changed.

ItemEvent An item has been selected (or deselected)


within a checkbox, choice menu, or list.

TextEvent The contents of a text area or text field


have changed.
Events
Low-level Events:
 Low-level events include moving the mouse or
pressing a key.
 One low-level event is WindowEvent, which
occurs when the status of a window has changed.
 In particular, a WindowEvent occurs when
the user attempts to close a window.
Interfaces
 Event-handling requires the use of interfaces.
 An interface looks like a class, except that its methods
aren’t fully defined.
 Each method in an interface has a name, a parameter
list, and a result type, but no body.
 One common interface is named ActionListener:
public interface ActionListener extends EventListener
{
public void actionPerformed(ActionEvent evt);
}
 This resembles a class declaration, except that the
word class has been replaced by interface, and
the actionPerformed method has no body.

UNIT-III Event Handling


Creating Event Listeners

 To handle an event, it’s necessary to create an


event listener object.
 This object will be “registered” with a component;
when an event occurs that involves the
component, one of the listener’s methods will be
called.
 An event listener will be an instance of a “listener
class” defined by the programmer.

UNIT-III Event Handling


Creating Event Listeners
• A listener class must implement one of the
interfaces that belong to the java.awt.event
package.
• Listener interfaces for high-level events:
Interface Name Required Method
ActionListener actionPerformed(ActionEvent evt)
AdjustmentListener adjustmentValueChanged(AdjustmentEven evt)
ItemListener t
itemStateChanged(ItemEvent evt)
TextListener textValueChanged(TextEvent evt)

• Each interface contains a single method. The


access modifier for each method is public, and
the return type is void.
Creating Event Listeners

 There’s a similar set of listener interfaces for


low-level events.
 The listener interface for WindowEvent
is named WindowListener.
Creating Event Listeners
 Pressing a button is an action event, so the listener
class for a button would need to implement the
ActionListener interface.
 To implement this interface, the class must define a
public void method named actionPerformed
with a parameter of type ActionEvent.
An example of a listener for an action event:
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {

}
}
Creating Event Listeners
 After writing a listener class, the next step is to
create an instance of the class and connect it to a
particular component.
 In the simplest case, a single listener object will
be attached to a single component.
 Suppose that b is a Button object:
Button b = new Button("Change Color");

 A listener object can be created by using the


constructor for the listener class:
ButtonListener listener = new ButtonListener();
Creating Event Listeners

 listener can now be registered as an action


listener for the button:
b.addActionListener(listener);

 It’s sometimes possible to save a statement by


combining the creation of the listener object with
the call of addActionListener:
b.addActionListener(new ButtonListener());
Creating Event Listeners

 Calling addActionListener creates a link


between the Button object and its listener:

 When the user presses the button, the


ButtonListener object’s actionPerformed
method will be called.
Creating Event Listeners

 Because ButtonListener implements the


ActionListener interface, the compiler can
verify that it has an actionPerformed method.

 The ActionListener interface acts as a sort of


contract that ButtonListener agrees to honor.

 It’s an error to pass an object to


addActionListener unless the object belongs
to a class that implements ActionListener.
Creating Event Listeners
 The ButtonTest program displays a
“Testing”
button, but pressing the button has no effect.

Making the button
class that work involves
implements defining a listener
the ActionListener
interface, creating an instance of the class, and
attaching it to the button.
 The ButtonTest2 program is similar to
ButtonTest, but the window will close when the
button is pressed.
 Changes are highlighted in bold.
ButtonTest2.java
// Displays a frame containing a single window"
"Close
// button. The frame can be closed by pressing the button.
import java.awt.*;
import java.awt.event.*;

// Driver class
public class ButtonTest2
{
public static void main(String[] args)
{
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);
}
}
// Frame class
class ButtonTestFrame extends Frame {
public ButtonTestFrame(String title) {
super(title);
setLayout(new FlowLayout());
Button b = new Button("Close window");
add(b);
b.addActionListener(new ButtonListener());
}
}

// Listener for button


class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
Creating Event Listeners

Frame created by the ButtonTest2 program:


Creating Event Listeners

Pressing the “Close window” button causes


a call of the actionPerformed method
for the button’s listener object.
This method calls System.exit, which
causes the program to terminate and the
frame to disappear.
When a program terminates, any windows
that it created are automatically closed.
Adapter Classes

 To make the Close button work, a


WindowEvent listener is needed.
 A class that implements the WindowListener
interface would have to contain seven methods.
 There’s an easier technique: use the
WindowAdapter class from the
java.awt.event package.
 This class implements the WindowListener
interface, although the methods that it provides
are all empty.
Adapter Classes

 The listener class will extend the


WindowAdapter class and override the
windowClosing method.
 It will then inherit all the other methods it needs.
 WindowAdapter is an example of an adapter
class—a class that can be extended instead of
implementing an interface.
 Java provides matching adapter classes for most
interfaces that have two or more methods.
Adapter Classes

The ButtonTest3 program is a


modification of ButtonTest2.
The new WindowCloser class extends
WindowAdapter and provides a
windowClosing method of its own.
The constructor for ButtonTestFrame
now calls addWindowListener to install a
WindowCloser object as a listener for
window events.
ButtonTest3.java
// Displays a frame containing a single
"Close
// button. The frame window"
can be closed by pressing either the
// "Close window" button or the frame's "close" button.

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

// Driver class
public class ButtonTest3 {
public static void main(String[] args) {
Frame f = new ButtonTestFrame("Button Test");
f.setSize(150, 100);
f.setVisible(true);
}
}
// Frame class
class ButtonTestFrame extends Frame {
public ButtonTestFrame(String title) {
super(title);
setLayout(new FlowLayout());
Button b = new Button("Close window");
add(b);
b.addActionListener(new ButtonListener());

// Attach window listener


addWindowListener(new WindowCloser());
}
}

// Listener for button


class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
}
// Listener for window
class WindowCloser extends WindowAdapter
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
}
Adapter Classes
 When a window event occurs, one of the
methods in the WindowCloser class will be
called.
 If the event is caused by the user attempting to
close the window, the windowClosing method
is called, and the program terminates.
 Any other window event will cause one of
WindowCloser’s inherited methods to be
called.
 These methods are empty, so nothing will
happen.
ChangeColor.java
// Displays a frame containing a single Pressing the
// button.
button causes the background of the frame to change from
// white to black or from black to white.

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

// Driver class
public class ChangeColor {
public static void main(String[] args) {
Frame f = new ChangeColorFrame("Change
Color");
f.setSize(160, 100);
f.setVisible(true);
}
}
// Frame class
class ChangeColorFrame extends Frame {
public ChangeColorFrame(String title) {
// Set title, layout, and background color
super(title);
setLayout(new FlowLayout());
setBackground(Color.white);

// Add "Change color" button to frame and attach


listener
Button b = new Button("Change color");
add(b);
b.addActionListener(new ButtonListener());

// Attach window listener


addWindowListener(new WindowCloser());
}
// Listener for button
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
if (getBackground() == Color.white)
setBackground(Color.black);
else
setBackground(Color.white);
}
}

// Listener for window


class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
}
Attaching Listeners to Multiple
Components
 If a program has two buttons, one possibility is to attach
the second button to the same ButtonListener object:

 The ButtonListener object’s actionPerformed


method will be called when either button is pressed.
Using Multiple Listeners

 The other possibility is to create a different


listener object for the second button:
Using Multiple Listeners

 The second listener could be an instance of a


different listener class:
Determining the Source of an
Event
If two or more buttons are connected to a
single listener, its actionPerformed
method will need to determine which button
was pressed.
Ways to solve this problem:
– Compare the source of the event (the component that
triggered the method call) to see which Button object
it matches.
– Test the event’s action command to see which button
label it matches.
The getSource Method

• If evt is an instance of any event class, the source


of the event can be found by calling getSource:
Object source = evt.getSource();
• Because events can be caused by a variety of
components, getSource returns an Object
reference.
• To determine which component fired the event, the
value returned by getSource can be compared
with the variables containing the components:
if (source == testButton) …
The getActionCommand Method
 The other way to determine the origin of a button
press is to use the getActionCommand method.
String label = evt.getActionCommand()
 This method can be;used only with action events,
such as button presses.
 In the case of a button press, getActionCommand
returns the label on the button.
 A statement that checks whether the button labeled
"Testing" was pressed:
if (label.equals("Testing")) …
ChangeColor2.java
// Displays a frame containing two Pressing the
// buttons. of the frame.
// "Lighter"
Pressing thebutton lightens
"Darker" the
button darkens the background.
background
import java.awt.*;
import java.awt.event.*;

// Driver class
public class ChangeColor2 {
public static void main(String[] args) {
Frame f = new ChangeColorFrame("Change Color");
f.setSize(160, 100);
f.setVisible(true);
}
}
// Frame class
class ChangeColorFrame extends Frame {
public ChangeColorFrame(String title) {
// Set title, layout, and background color
super(title);
setLayout(new FlowLayout());
setBackground(Color.gray);
// Create button listener
ButtonListener listener = new ButtonListener();

// Add "Lighter" button to frame and attach


listener
Button b = new
Button("Lighter"); add(b);
b.addActionListener(listener);
// Add "Darker" button to frame and attach
listener
b = new Button("Darker");
add(b);
b.addActionListener(listener);
// Attach window listener
addWindowListener(new WindowCloser());
// Listener for both buttons
class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent evt) {
Color currentBackground = getBackground();
String buttonLabel = evt.getActionCommand();
// Test label on button and change background color
if (buttonLabel.equals("Lighter"))
setBackground(currentBackground.brighter());
else
setBackground(currentBackground.darker());
}
}

// Listener for window


class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
} }
The brighter and darker methods
belong to the Color class.
brighter returns a brighter version
of the Color object that called it;
darker returns a darker version.
ConvertTemp.java
// Converts a Fahrenheit temperature entered by the user to
// Celsius, or vice versa

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

// Driver class
public class ConvertTemp {
public static void main(String[] args) {
Frame frame =
new ConvertTempFrame("Temperature Conversion");
frame.setSize(150, 75);
frame.setVisible(true);
}
}
// Frame class
class ConvertTempFrame extends Frame {
private TextField fahrenField = new TextField();
private TextField celsiusField = new TextField();

// Constructor
public ConvertTempFrame(String title) {
// Set title for frame and choose layout
super(title);
setLayout(new GridLayout(2, 2));

// Add Fahrenheit label and text field to frame;


attach
// listener to text field
add(new
Label("Fahrenheit"));
add(fahrenField);
fahrenField.addActionListener(n
ew
FahrenheitListener());
// Add Celsius label and text field to frame; attach
// listener to text field
add(new Label("Celsius"));
add(celsiusField);
celsiusField.addActionList
ener(new
CelsiusListener());
// Attach window listener
addWindowListener(new
} WindowCloser());

// Listener for fahrenField


class FahrenheitListener implements ActionListener
{
public
Stringvoid actionPerformed(ActionEvent
fahrenheitString evt) {
= fahrenField.getText();
double fahrenheit =
double Convert.toDouble(fahrenheitString);
celsius
celsius = = (fahrenheit
Math.rint(celsius - 32.0)
* 100.0) * 5.0 / 9.0;
/ 100.0;
celsiusField.setText(celsius + "");
}
}
// Listener for celsiusField
class CelsiusListener implements ActionListener
{
public
Stringvoid actionPerformed(ActionEvent
celsiusString evt) {
= celsiusField.getText();
double celsius =
double Convert.toDouble(celsiusString);
fahrenheit
fahrenheit = celsius * *9.0
= Math.rint(fahrenheit / 5.0 + 32.0;
100.0) / 100.0;
fahrenField.setText(fahrenheit + "");
}
}

// Listener for window


class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent {
evt)
System.exit(0);
}
} }

g
ShowDefinition.java
// Shows the definition of a term

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

// Driver class
public class ShowDefinition {
public static void main(String[] args) {
Frame f = new ShowDefinitionFrame("Show
Definition");
f.setSize(300, 160);
f.setVisible(true);
}
}
// Frame class
class ShowDefinitionFrame extends Frame
{ private List termList = new List();
private TextArea definitionArea = new
private TextArea();
String[]
{"Button", terms"Choice",
"Checkbox", = "Label",
"List", "Scrollbar", "TextArea",
"TextField"};
private String[]
{"A labeled definitions
button that can\nbe= pressed",
"A box that can be clicked\n\"on\"
"A or \"off\"",
"A menu that displays one\nitem at a time",
string that can be\npositioned next to " +
"other\ncomponents",
"A scrolling list of items",
"A sliding bar that can be\neither horizontal " +
or
"A "vertical",
multiline area in which\ntext can be displayed " +
"or\nedited",
"A single line of text that\ncan be displayed " +
"or\nedited"};
// Constructor
public ShowDefinitionFrame(String title)
{
// Set title for frame
super(title);
// Put terms in term list; add term list to frame
for (int i = 0; i < terms.length; i++)
termList.add(terms[i]);
termList.addItemListener(new
ListListener());
add("West", termList);
// Make definition area not editable and add to frame
definitionArea.setEditable(false);
add("Center", definitionArea);

// Attach window listener


addWindowListener(new
} WindowCloser());
// Listener for termList
class ListListener implements ItemListener {
public void itemStateChanged(ItemEvent evt)
{
int index = termList.getSelectedIndex();
definitionArea.setText(definitions[index]);
}
}
// Listener for window
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
} }

UNIT-III Event Handling


PickColor.java

UNIT-III Event Handling


PickColor.java
// Allows the user to pick a color by moving three scrollbars

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

// Driver class
public class PickColor {
public static void main(String[] args) {
Frame f = new PickColorFrame("Pick Color");
f.setSize(150, 200);
f.setVisible(true);
}
}

UNIT-III Event Handling


PickColor.java

// Frame class
class PickColorFrame extends Frame
{private Label redLabel = new Label("Red = 128", Label.CENTER);
private Label greenLabel = new Label("Green = 128", Label.CENTER);
private Label blueLabel = new Label("Blue = 128", Label.CENTER);
private Scrollbar redBar =
new Scrollbar(Scrollbar.HORIZONTAL, 128, 1, 0, 256);
private Scrollbar greenBar =
new Scrollbar(Scrollbar.HORIZONTAL, 128, 1, 0, 256);
private Scrollbar blueBar =
new 128, 1, 0, 256);
Scrollbar(Scrollbar.HORIZONTAL,
// Constructor
public PickColorFrame(String title) {
// Set title, background color, and
layout
super(title);
setBackground(new Color(128, 128, 128));
setLayout(new GridLayout(6, 1));
PickColor.java
// Create scrollbar listener
ScrollbarListener listener = new ScrollbarListener();

// Add red scrollbar and label to frame; attach


// listener to scrollbar
add(redBar);
redBar.addAdjustmentListener(listener);
add(redLabel);
// Add green scrollbar and label to frame; attach
// listener to scrollbar
add(greenBar);
greenBar.addAdjustmentListener(listener);
add(greenLabel);
// Add blue scrollbar and label to frame; attach
// listener to scrollbar
add(blueBar);
blueBar.addAdjustmentListener(listener);
add(blueLabel);

// Attach window listener


addWindowListener(new WindowCloser());
}
PickColor.java
// Listener for all scrollbars
class ScrollbarListener implements AdjustmentListener
{
public void adjustmentValueChanged(AdjustmentEvent
evt) {
int red = redBar.getValue();
int green = greenBar.getValue();
int blue = blueBar.getValue();

redLabel.setText("Red = " + red);


greenLabel.setText("Green = " + green);
blueLabel.setText("Blue = " + blue);

Color newColor = new Color(red, green, blue);


redLabel.setBackground(newColor);
greenLabel.setBackground(newColor);
blueLabel.setBackground(newColor);
}
}
PickColor.java
// Listener for window
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
}
}

You might also like