Java Cha 2
Java Cha 2
Java Cha 2
Introduction
Using a layout manager to arrange components within a
container may result in a GUI that looks good, but in order to
make it do anything ( for example to get user input), you have to
handle events.
An event typically signifies an
action by the user, such as striking a key or clicking the mouse
over a JButton component.
For example, an event can be generated when the value of
component's property changes or when a specified amount of time
elapses.
In the event handling process, there are three important players :
Event, Event Source, and Event Listener (or Handler)
2
Event and Event Source
An event can be defined as a type of signal to the program
that something has happened.
3
Event and Event Source…..
An event is created when an event occurs (i.e., user interacts
with a GUI component).
An event is an instance (object) of an event class.
The component on which an event is fired or generated is
called the source object or source component (Event
source).
Example
A button is the source object for a button-clicking action
event.(i.e. an ActionEvent Object is generated. )
4
Event and Event Source ….
5
User Action, Source Object, and Event Type
Source Event Type
User Action Object Generated
Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select item(s) JList ListSelectionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent
6
Listeners, Registrations, and Handling Events
7
Listeners, Registrations, and Handling Events
Two things needed for an object to be a listener for an event on
the source object.
1) The listener object must be an instance of the corresponding
event- listener interface to ensure that the listener has the
correct method for processing the event.
10
Steps for Creating GUI Applications with Event Handling
Example 1:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class SimpleEventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
12
Listeners, Registrations, and Handling Events…
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}// End of main() method
}//end of class SimpleEventDemo
13
Listeners, Registrations, and Handling Events…
Example 2
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.event.*;
public class MyEvent extends JFrame {
JButton b1;
public MyEvent(){
super("Window Title: Event Handling");
b1 = new JButton("Click Me");
add(b1, BorderLayout.NORTH);
setSize(200,200);
setVisible(true);
14 }
Listeners, Registrations, and Handling Events…
15
Event-listeners
ActionListener Method
Contains exactly one method
16
Event-listeners…
MouseListener Methods
17
Event-listeners…
MouseMotionListener Methods
18
Event-listeners…
WindowListener Methods
19
Event-listeners…
Other Listeners are
KeyListener
Methods
keyPressed(KeyEvent e) - Invoked when a key has been pressed.
keyReleased(KeyEvent e) - Invoked when a key has been released.
keyTyped(KeyEvent e) - Invoked when a key has been typed.
FocusListeners
Methods
focusGained(FocusEvent e) - Invoked when a component gains the
keyboard focus.
focusLost(FocusEvent e) - Invoked when a component loses the
keyboard focus.
ItemListeners
Method
itemStateChanged(ItemEvent e) - Invoked when an item has been
selected or deselected by the user
20
Event-listeners…
TextListner
Method
textValueChanged(TextEvent e) - Invoked when the value of
the text has changed.
ContainerListner
Methods –
componentAdded(ContainerEvent e) - Invoked when a
component has been added to the container.
componentRemoved(ContainerEvent e) - Invoked when a
component has been removed from the container.
21
Sources-events-listeners
Source Event object Listener Methods
<state change> (argument:
corresponding
event)
Mouse MouseEvent MouseListener mouseClicked
<mouse clicked, pressed, mousePressed
dragged, moved/ entered, mouseReleased etc
exited a component etc>
MouseMotionListener mouseDragged
mouseMoved
22
Sources-events-listeners
Source Event Listener Methods
<state change> (argument:
corresponding
event)
Button ActionEvent ActionListener ActionPerformed
<GUI button clicked>
23
Inner Class Listeners …
public class Test { // OuterClass.java: inner class demo
... public class OuterClass {
} private int data;
24
Inner Class Listeners …
25
Inner Class….
Inner classes can make programs simple and concise.
An inner class can be declared public, protected, or
private subject to the same visibility rules applied to a
member of the class.
26
Inner Class Example
Example 1:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class SimpleEventDemo {
public static void main(String[] args) {
JFrame frame = new JFrame();
27
Inner Class Example…
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}// End of main() method
29
Anonymous Inner Classes ….
Example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
30
Anonymous Inner Classes…
jbtOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("It is OK");
}
});
frame.setTitle("SimpleEventDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
} // end of class SimpleEventDemo
31
Multiple Listeners for a Single Source
Example
setLayout(new FlowLayout());
add(jbtOK);
add(jbtCancel);
jbtOK.addActionListener(firstListener);
jbtCancel.addActionListener(firstListener);
jbtOK.addActionListener(secondListener);
jbtCancel.addActionListener(secondListener);
32
Multiple Listeners for a Single Source
private class FirstListener implements ActionListener {
/** This method will be invoked when a button is clicked */
public void actionPerformed(ActionEvent e) {
System.out.print("First listener: ");
if (e.getSource() == jbtOK) {
System.out.println("The OK button is clicked");
}
else if (e.getSource() == jbtCancel) {
System.out.println("The Cancel button is clicked");
}
}
}
33
Multiple Listeners for a Single Source
private class SecondListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.print("Second listener: ");
if (e.getActionCommand().equals("OK")) {
System.out.println("The OK button is clicked");
}
else if (e.getActionCommand().equals("Cancel")) {
System.out.println("The Cancel button is clicked");
}
}
}
34
Adapter classes
Many event-listener interfaces, such as MouseListener and
MouseMotionListener, contain multiple methods.
It is not always desirable to declare every method in an event-
listener interface.
For instance, an application may need only the mouseClicked
handler from MouseListener or the mouseDragged handler
from MouseMotionListener.
For many of the listener interfaces that have multiple methods,
packages java.awt.event and javax.swing.event provide event-
listener adapter classes.
An adapter class implements an interface and provides a
default implementation (with an empty method body) of each
35 method in the interface.
Adapter classes…
You can extend an adapter class to inherit the default
implementation of every method and subsequently override
only the method(s) you need for event handling.
The convenience adapter is named XAdapter for XListener.
Examlpe:
WindowAdapter is a convenience listener adapter for
WindowListener.
36
Adapter classes…
37
Exercise:
Develop a scientific calculator in java
38