BEEN Advanced Java Programming Reference Note
Unit-3
Event Handling
Introduction
Event
Change in the state of an object is known as event ie. event describes the change in state of
source. Events are geuerated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character
tough keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Types of Event
The events can be broadly classified into two categories:
+ Foreground Events: Those events which require the direct interaction of user. They are
generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a
character through keyboard, selecting an item from list, scrolling the page ete
= Background Events: Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if
an event occurs. This mechanism have the code which is known as event handler that is
executed when an event occurs. Java Uses the Delegation Event Model to handle the events.
Delegation Event Model
The delegation event model, which defines standard and consistent mechanisms to generate
and process events. Its concept is quite simple: a source generates an event and sends it to one
or more Jisteners. In this scheme, the listener simply waits until it receives an event. Once
received, the listener processes the event and then retums. The advantage of this design is that
the application logic that processes events is cleanly separated from the user interface logic that
generates those events.
In the delegation event model, listeners need to be registered with the source object so that the
listener can receive the event notification. This provides an important benefit: notifications are
sent only to listeners that want to receive them.
There are three things that are done in event handling:
1. Create a class that represents the event handler.
2. Implement an appropriate interface called “event listener interface” in the above class.
3. Register the event handler
Collegenote Prepared By: Jayanta PoudelWO Advanced Java Programming Reference Note
The delegation event model has three main components:
+ Events: An event is a change of state of an object.
+ Events Source: Event source is an object that generates an event.
+ Listeners: A listener is an object that listens to the event. A listener gets notified when an
event occurs.
EVENT
SOURCE On.
‘ister
“ |
EVENT
LISTENER
Event Classes
Event classes are the classes that represent events at the core of java’s event handling
mechanism. At the root of the Java event class hierarchy is EventObject, which is in java.util.
Itis the superclass of all events.
The class AWTEvent, defined within the java.awt package, is a subclass of EventObject. Itis
the superclass of all AWT-based events used by delegation event model
The main classes in java.awtevent.
Event Class Description
ActionEvent Generated when a button is pressed, alist item is doubleclicked, or a ment
item is selected
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponeniEven Generated when a components hidden, moved, resized, or becomes vible
ContainerEve Generated when a component is added to or removed from a con
FoousFvent ‘Generated when a component gains or loses keyboard focus,
Inputtvent Abstract superclass forall component input event classes
‘temEvent Generated when a check box or list item is clicked: also occurs when
a choice selection is made or a checkable menu item is selected or
deselected
KeyEvent input is recehed from the keyboard
MouseEveni ced, moved, clicked, pressed, or release
also generated when the mouse enters or exits a component.
MouseWheelEvent__| Generated when the mouse wheel is moved.
TextEvent ‘Generated when the value ofa ext area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconilied,
iconitfied, opened, oF quit.
Collegenote Prepared By: Jayanta PoudelAdvanced Java Programming Reference Note
Event Listener Interfaces
To handle events we must implement event listener interfaces. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, it must implement methods to receive and process these
notifications. The methods that receive and process events are defined in a set of interfaces
found in java.awtevent.
‘The list of commonly used event listener interfaces are:
‘Description
ActionListener
Defines one method to receive action events.
AdjustmentListener
Defines one method to receive adjustment events
‘ComponentListener
Defines four methods to recognize when a component is hidden, moved,
resized, or shown.
‘ContainerListener
Defines two methods to recognize when a component is added to or
removed from a container.
FocusListener
Defines two methods to recognize when a component gains or loses
Keyboard focus.
TemListenes
Defines one method to recognize when the state of an item changes.
KeyListener
Defines three methods to recognize when a key is pressed, released, or ped.
Mousel.istener
Defines five methods to recognize when the mouse is clicked, enters a
component, exits a component, is pressed, ors released,
MouseMotionListener
Defines two methods to recognize when the mouse is dragged or moved.
MouseWheelListencr
Defines one method to recognize when the mouse wheel is moved
TexiListener
Defines one method to recognize when a text value changes,
WindowFocuslisiener
Defines two methods to recognize when a window gains or loses input focus.
WindowListener
Defines seven methods to recognize when a window is activated, closed,
deactivated, deiconified, iconified, opened, or quit
Collegenote
Prepared By: Jayanta PoudelBEEN Advanced Java Programming
He indling Action Events
Reference Note
The ActionE vent is generated when button is clicked or the item of a list is double-clicked. The
listener related to this class is ActionListener. To handle an action event, a class must
implements the ActionListener interface
To have any component listen for an ActionEvent, we must register the component with an
ActionListener as: component.addActionListener(new MyActionListener(); and then write
the public void actionPerformed(ActionEvent e); method for the component to react to the
event.
Example
import java.awt. event ActionEvent;
import java.awt.event. ActionListener;
import javax.swing.JButton;
import javax.swing JFrame;
import javax.swing JTextField;
class EventHandling extends JFrame implements ActionListener
é
SlextField if:
EventHandling (
t
if = new TextField ();
thsetBounds (60, 50, 170, 20);
JButton button = new JButton ("Show");
button.setBounds (90, 140, 75, 40);
button.add ActionListener (this);
add (button);
add (if);
setSize (250, 250);
setLayout (null);
setVisible (true);
ih
@Override
public void actionPerformed (ActionE vent e)
sf setText ("Hello World"),
3
public static void main (String args[])
f
new EventHandling();
i
}
Output:
Hallo wens
Collegenote
Prepared By: Jayanta PoudelBED Advanced Java Programming Reference Note
He indling Key Events
The KeyEvent is generated in case of key presses and key depresses on text fields such as
JTextField and JTextArea. One example of KeyEvent is user typing in a textfield. The listener
associated with this class is KeyListener. To handle a key event, a class must implements the
KeyListener interface
To have any component listen for a KevEvent, we must register the component with
KeyListener as: component.addKeyListener(new MyKeyListener()); and then write the
public void keyPressed(KeyEvent e);
public void keyTyped(KeyEvent e);
public void keyReleased(KeyEvent e); methods for the component to react to the event.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EventHandling extends JFrame {
SITextField t1 = new JTextField(10);
TextField 12 = new JTextField(10);
public EventHandling() {
seiLayout(new FlowLavout());
setSize(200, 200);
setVisible(true);
setDefanltCloseOperation(JFrame EXIT_ON_CLOS
add(tl);
add(2);
12.setRditableffalse);
tl.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
String copy = tl.getText();
12.setText(copy);
,
dD:
f
public static void main(Stringf] args) {
new EventHandling);
i
}
Collegenote Prepared By: Jayanta PoudelBEET Advanced Java Programming Reference Note
ig Focus Events
The FocusEvent is generated when a component gains or loses keyboard focus. The listener
for this class is FocusListener. To handle a focus event, a class must implements the
FocusListener intertace.
To have any component listen for an FocusEvent, we must register the component with an
FocusListener as: component.addFocusListener(new My FocusListener(); and then write the
public void focusGained(FocusEvent e);
public void focusLost(FocusEvent e); methods for the component to react to the event.
Example
import java.awt.*;
import java.awt.event.*:
import javax.swing.*;
public class EventHandling extends JFrame implements FocusListener {
private JTextField tf1;
private JTextField tf2;
public EventHandling() {
setTitle("Focus Listener Example");
setLayout(new GridLayout(2, 1));
setSize(200, 200);
ofl = new TextField);
If? = new JTextField():
add(ifD);
add(p2);
#l.addFocusListener(this);
P2.addFocusListener(this);
setVisible(true);
/
public void focusGained(FocusEvent e) {
if (e.getSource() == ffl) {
‘l-setBackground(Color. YELLOW);
J else if (e.getSource() ~~ 2) {
f2.setBackground(Color. YELLOW);
}
}
public void focusLost(FocusEvent e) {
if (e getSource() == ffl) {
Output:
{fl setBackground(Color. WHITE); ee
} else if (e.getSource() == f2) { [Bj FocustistenerExam., — O xX
12.setBackground(Color. WHITE); [--
i Besttootoaller
i
public static void main(String[] args) {
new EventHandling();
J
j
Collegenote Prepared By: Jayanta PoudelBENE Advanced Java Programming Reference Note
He indling Mouse Events
The MouseEvent is generated when mouse action (dragged, moved, clicked, pressed, or
released) occurred in a component, also generated when the mouse enters or exits a component
The listener for this class is MouseListener. To handle a mouse event, a class must implements
the MouseListener interface.
To have any component listen for a MouseEvent, we must register the component with
MouseListener as: component.addMouseListener(new MyMouseListener()); and then write
the
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseE vent ¢);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseE vent e);
public void mouseExited(MouseEvent e); wethods for the component to react to the event.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseListenerEvanple extends JFrame implements MouseListener {
private JButton button;
public MouseListenerExample) {
setTitle("Handling Mouse Listener");
300, 150);
new JButton("Click me?”);
add(button);
button.addMouseListener(this),
setVisible(true);
i
public void mouseClicked(MouseEvent e) {
button.setText("Clicked!”),
i
public void mouseEntered(MouseEvent e) {
button.setBackground(Color. RED);
}
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseE vent e) { }
public void mouseReleased(MouseE vent e) { }
public static void main(String{] args) {
new MouseListenerExample();
i
J
Collegenote Prepared By: Jayanta PoudelBEEN Advanced Java Programming Reference Note
He indling Window Event
The WindowEvent is generated whenever we change the state of window. Closing, activating,
deactivating, opening, quiting, minimizing, maximizing a window come under this
class. Window event is generated by component such as JFrame, JIntemalFrame, JDialog etc
To handle a window event, a class must implements the WindowListener interface.
To have any component listen for a WindowEven, we must register the component with
WindowListener as: component.addWindowListener(new MyWindowListener()); and then
write the
public void window Opened(WindowEvent e);
public void windowClosing(WindowE vent e);
‘public void windowClosed(WindowE vent e);
public void windowIconified(WindowEvent e);
Public void windowDeiconified(WindowEvent e);
Public void windowActivated(WindowEvent e);
public void windowDeactivated( WindowEvent e); methods for the component to react to the
event.
mple
import java.awt.*;
import java.awt.event.*:
import javax.swing.*;
public class WindowListenerExample extends JFrame implements WindowListener {
ILabel label;
public WindowListenerExample() {
setTitle("Handling Window Listener");
(300, 150);
new JLabel("Window opened.");
add(label);
addWindowListener(this);
setVisible(true);
i
public void windowOpened(WindowEvent e) {
label setText("Window opened.");
/
ipublie void windowClosing(WindowEvent e) {
label setText("Window closing.");
J
‘public void windowClosed(WindowEvent e) { }
public void windowLconified WindowEvent e) {
label setText("Window minimized");
A
public void windowDeiconified(WindowEvent e) {
label serText("Window restored.");
i
public void windowActivated(WindowEvent e) {
label setText("Window activated.");
i
public void windowDeactivated(WindowEvent e) {
label setText("Window deactivated");
Collegenote Prepared By: Jayanta PoudelBEEN Acvanced Java Programming Reference Note
}
public static void main(Stringl] args) {
new WindowListenerExample();
}
i
Handling Item Event
Item event is generated whenever user selects or deselects a selectable object such as radio
button, checkbox or list. To handle an item event, a class must implement the MemListener
interface
To have any component listen for an JtemEvent, we must register the component with an
IremListener as: component.addltemListener(new MyltemListener()); and then write the
‘public void itemStateChanged(ItemEvent e); method for the component to react to the event.
The stateChange of any ItemBvent instance takes one of the following values:
ItemEvent SELECTED, ItemEvent DESELECTED
Example
import javax.swing.*;
import java.awt.*;
import java.awtevent.*;
public class liemListenerExample implements ItemListener {
JFrame frame;
ICheckBox checkRox;
Mabel label;
public HiemListenerExample() {
frame = new JFrame("IemListener Example");
frame.setDefaultCloseOperation(JFrame.EXIT ON CLOSE);
checkBox = new JCheckBox("Check Me");
label = new JLabel();
checkBox.addltemListener (this);
JPanel panel = new JPanel);
panel.add(checkBox);
panel add(label);
frame.add{panel);
-frame.setSize(200, 200);
“Frame.setVisible(irue);
i
public void ifemStateChanged(liemEvent e) {
if (e.getStateChange() ~~ IremEvent. SELECTED) {
label.setText("Checkbox is checked);
J else if (e.getStateChange() == ItemEvent. DESELECTED) {
label setText("Checkbox is unchecked");
3
,
ipublie static void main(Stringf] args) {
new ItemListenerExample();
i
i
Collegenote Prepared By: Jayanta PoudelWED Advanced Java Programming Reference Note
Adapter Classes
‘Many of the listener interfaces have more than one method. When we implement a listener
interface in any class then we must have to implement all the methods declared in that interface
because all the methods in an interface are final and must be override in class which implement
it, Adapter class makes it easy to deal with this situation.
An adapter class provides empty implementations of all methods defined by that interface.
Adapter classes are very usefill if we want to override only some of the methods defined by
that interface. We can define a new class to act as an event listener by extending one of the
adapter classes and implementing only those events in which we are interested.
‘Adapter Class, Listener Interface
omponentAdapter ComponentListener
ContainerLis
Focuslistener
KeyAdapter KeyListener
MouseAdapter “MouseListener and (as of JDK 6)
MouseMotionListener and MouseWheelListener
M
For example, the KeyListener interface contains three methods KeyPressed(), KeyReleased()
and KeyTyped(). If we implement this interface, we have to give implementation of all these
three methods. However, by using the KeyAdapter class, we can override only the method that
is needed. This can be shown in the code example given below:
Using KeyListener
import javax.swing.*;
import java.awt.*;
import java.awtevent.*:
public class KeyListenerExample extends JFrame implements KeyListener {
Iabel outputLabel;
public KeyListenerExample() {
setTitle("KeyListener Example");
setSize(400, 200);
setDefauliCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
ousputLabel = new JLabel("Press a key");
add(ouiputLabel),
addKeyListener(this);
setVisible(true);
i
@Override
public void keyPressed(KeyEvent e) {
ouputLabel setText(Key Pressed: " + e.getKeyChar());
i
@Override
public void keyReleased(KeyEvent e) {
Collegenote Prepared By: Jayanta PoudelAdvanced Java Programming Reference Note
outputLabel.setText("Key Released: " + e,getKeyChar());
=0; i)
t
copyUserInput ~ copyUserInput + userInput.charat(i);
}
if (copyUserInput.equalsignoreCase(userInput))
f
Collegenote Prepared By: Jayanta PoudelWED Advanced Java Programming Reference Note
outputTextField setText("String is palindrome."
j
else
t
outputTextField serText("Siring isn't a palindrome.");
}
3
MD
reverseButton.addActionListener(new ActionListener()
t
@Override
public void actionPerformed(ActionEvent e)
é
String reverseUserInput="";
String userInput = inputTextField getText);
int length = userInput.length();
for (int i= length-1; i>~0; ==)
e
reverseUserInpul
f
reverseUserinput + userInput.charAt(i);
outputTextField.setText("Reverse String is: "+ reverseUserInpu);
}
DD
findVowelButton.addActionListener(new ActionListener()
t
@Override
public void actionPerformed(ActionEvent e)
char[] vowel={a",'e',"''0',u'A''E',T,0'",U};
String userlnput ~ inputTextField getText();
int length = userinput length);
char[] extracteaVowel= new charflength];
String showVowel
for (int i =0; i<=lengihel; i++)
#
for (intj
t
iffuserInput.charAt(i
t
extractedVowelfi] = userInput.charAi(i);
showVowel = showVowel + String valueOffextractedVowelfi]);
}
}
| F< =vowel length-1; j++)
vowelfj])
i
Collegenote Prepared By: Jayanta PoudelBEET Advanced Java Programming
outputTextField.setText("Vowels: "+showVowel);
3
Di
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE),
setVisible(irue);
A
public static void main(Stringl] args)
t
new SwingExample();
ch
}
Reference Note
Please let me know if Tmissed anything or
anything is incorrect.
joudeljayanta99\
Collegenote
Prepared By: Jayanta Poudel