7/28/2019 04_EventHandling
1/49
95-712 OOP Java 1
Event Handling Overview Listeners, Adapters and
Event Sources Inner classes Event Handling Details
Applets and GUI Applications
Event Handling
7/28/2019 04_EventHandling
2/49
95-712 OOP Java 2
Event Handling
Used by the Abstract Window Toolkit (AWT) for basic GUI
programming Java 1.0 Used by Swing -- Better components than AWT Java 2 Used by JavaBeans -- reusable software components, like
Visual Basic, that can be manipulated
in a builder tool
7/28/2019 04_EventHandling
3/49
95-712 OOP Java 3
Babysitting
A baby in the home needs attention.Many events surrounding the baby are not easily ignored.Events can be of different types.
7/28/2019 04_EventHandling
4/49
95-712 OOP Java 4
One possible source of events
7/28/2019 04_EventHandling
5/49
95-712 OOP Java 5
BabysittingBefore responding to an event, a babysitter typically takes noteof the source and the type of event.
7/28/2019 04_EventHandling
6/49
95-712 OOP Java 6
Babysitting
The sitter needs to know both theevent type and the event source.
Event source
Event type
Handler
7/28/2019 04_EventHandling
7/49
95-712 OOP Java 7
Event Handling
The window manager software may generate hundreds of differentevents.
Examples include mouse clicks, mouse movements, key strokes,and timer ticks.
A programmer is typically interested in a small subset of all of the possible events that may occur.
7/28/2019 04_EventHandling
8/49
95-712 OOP Java 8
Events and Event Objects
Since events may be of different types but still exhibit someshared traits (inheritance) Java represents the event classes
in a hierarchy.
The root class is called java.util.EventObject. The only commonfeature shared by all events is a source object. So we find thefollowing method in the EventObject class :
public Object getSource();
7/28/2019 04_EventHandling
9/49
95-712 OOP Java 9
EventObject
AWTEvent
ActionEvent ComponentEvent
InputEvent WindowEvent
MouseEvent KeyEvent
Some classes andmethods in the eventhierarchy.
Object
String getActionCommand()
int getX()
char getKeyChar()
boolean isAltDown() Window getWindow()
7/28/2019 04_EventHandling
10/49
95-712 OOP Java 10
Event handling usually involves
three types of objects Objects are used to hold and report on information about the event. Objects are typically the source of events.
Objects, called listeners, are used to handle events.
7/28/2019 04_EventHandling
11/49
95-712 OOP Java 11
ExampleA mouseobject
An event objectthat describes,say, the x and y
coordinate of where the mousewas clicked
The listener object
has methods thatare called for
particular events
Event Source
Event data and methods
Listener
7/28/2019 04_EventHandling
12/49
95-712 OOP Java 12
ExampleA mouseobject
An event objectthat describes,say, the x and y
coordinate of where the mousewas clicked
The listener object
has methods thatare called for
particular events
ImplementsMouseListener
The event object is sentto a listener method
A mouse object must be told who its listener
is.
7/28/2019 04_EventHandling
13/49
95-712 OOP Java 13
The Listener There are different types of Listeners.
MouseListeners
WindowListenersScrollBarListenersEtc..
These Listeners are interfaces. Remember what an interface provides? If class X implements an interface then class X promisesto provide (at least) the methods declared in the interface.
7/28/2019 04_EventHandling
14/49
95-712 OOP Java 14
Some of the Listener Hierarchy
EventListener
ActionListener
abstract void actionPerformed(ActionEvent e);
MouseListener
abstract void mouseClicked(MouseEvent e)
KeyListener
7/28/2019 04_EventHandling
15/49
95-712 OOP Java 15
A Listener Interface
public interface MouseListener {
void mouseClicked(MouseEvent e);void mouseEntered(MouseEvent e);void mouseExited(MouseEvent e);void mouseReleased(MouseEvent e);
}//What does it mean if I claim that I implement this interface?
7/28/2019 04_EventHandling
16/49
95-712 OOP Java 16
An Example
// MouseSpyApplet.java
import java.applet.Applet;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;
7/28/2019 04_EventHandling
17/49
95-712 OOP Java 17
class MouseSpy implements MouseListener { public void mouseClicked(MouseEvent event)
{ System.out.println("Mouse clicked. x = "+ event.getX() + " y = " + event.getY());
} public void mouseEntered(MouseEvent event){ System.out.println("Mouse entered. x = "
+ event.getX() + " y = " + event.getY());}
public void mouseExited(MouseEvent event){ System.out.println("Mouse exited. x = "+ event.getX() + " y = " + event.getY());
} public void mousePressed(MouseEvent event){ System.out.println("Mouse pressed. x = "
+ event.getX() + " y = " + event.getY());}
public void mouseReleased(MouseEvent event){ System.out.println("Mouse released. x = "
+ event.getX() + " y = " + event.getY());}
}
I have to provideALL of these methods!!
7/28/2019 04_EventHandling
18/49
95-712 OOP Java 18
public class MouseSpyApplet extends Applet{ public MouseSpyApplet()
{ MouseSpy listener = new MouseSpy();
addMouseListener(listener);}
}
7/28/2019 04_EventHandling
19/49
95-712 OOP Java 19
Spying on the mouse
Java Applets need an HTML file.
7/28/2019 04_EventHandling
20/49
95-712 OOP Java 20
Another approachSuppose a friendly sole created this class:
public class MouseAdapter implements MouseListener {
void mouseClicked(MouseEvent e){}void mouseEntered(MouseEvent e){}void mouseExited(MouseEvent e){}void mousePressed(MouseEvent event) {}void mouseReleased(MouseEvent e){}
}
Now, suppose I extend this class. What must I provide?
7/28/2019 04_EventHandling
21/49
95-712 OOP Java 21
Only those methods that I am interested in.
The other methods, when called, do
nothing. Well visit this issue again later.
7/28/2019 04_EventHandling
22/49
95-712 OOP Java 22
Inner Classes
Nested Top Level Classes (not inner) Member Classes Local Classes Anonymous Classes
7/28/2019 04_EventHandling
23/49
95-712 OOP Java 23
Nested Top Level Class
Nested top-level classes are not inner classes. Use as a convenient way to group related classes Since the class must be static and has no 'this' pointer, it
has no access to the instance data of objects for itsenclosing class.
It behaves just like a 'normal' class or interface.
7/28/2019 04_EventHandling
24/49
95-712 OOP Java 24
//NestedTopLevelExample.java
class Top {int i,j;static class SomeClass { // static makes it top-level nested
int k;SomeClass() {
System.out.println("Constructing SomeClass");}void foo() { System.out.println("Hello"); }
}
Top() {System.out.println("Constructing a Top object");
}
}
7/28/2019 04_EventHandling
25/49
95-712 OOP Java 25
public class NestedTopLevelExample {
public static void main(String args[]) {
Top myTop = new Top();
Top.SomeClass myObject = new Top.SomeClass();myObject.foo();}
}Output
Constructing a Top objectConstructing SomeClassHello
7/28/2019 04_EventHandling
26/49
95-712 OOP Java 26
Member Classes (1)
Member classes (there is no such thing as a 'member interface)
This inner class (it's not a top-level class) has no statickeyword and can access the members of each object of its outer class.
The class 'appears in every instance'.
7/28/2019 04_EventHandling
27/49
95-712 OOP Java 27
The parent class must declare an instance of an innerclass, before it can invoke the inner class methods, assignto data fields (including private ones), and so on.
Unlike nested top-level classes, inner classes are notdirectly part of a package and are not visible outside theclass in which they are nested.
Inner classes are often used for GUI event handlers.
Member Classes (2)
7/28/2019 04_EventHandling
28/49
95-712 OOP Java 28
// MemberClassExample.javaclass Top {
int i = 33;public class SomeClass {// access the outer object's state.private int k = i;SomeClass() {
System.out.println("Constructing SomeClass");}void foo() { System.out.println("Hello"); }
}
Top() {System.out.println("Constructing a Top object");SomeClass sc = new SomeClass();System.out.println(sc.k);
}}
7/28/2019 04_EventHandling
29/49
95-712 OOP Java 29
public class MemberClassExample {
public static void main(String args[]) {
Top myObject = new Top();
}}
// OUTPUTConstructing a Top objectConstructing SomeClass33
7/28/2019 04_EventHandling
30/49
95-712 OOP Java 30
Local Classes
A local class is an inner class. Typically, a local classis declared within a method. It is not a member of anenclosing class. It is visible only within a block.
These classes are used primarily as "adapter classes".
For example, a block of code that creates a Button objectcould use a local class to define a simple implementation
of the ActionListener Interface. Then it could instantiatethis simple implementation and pass the resulting objectto the button's ActionListener method, thereby connectingthe button to the "callback" code that is executed whenthe button is pressed.
7/28/2019 04_EventHandling
31/49
95-712 OOP Java 31
// Local Class exampleclass Top {
int i = 33;
Top() { System.out.println("Constructing a Top object");// define a class within a methodclass Wow {
int t;Wow() { System.out.println("Building a Wow");
i = 8;t = 9;
}
}Wow h = new Wow();System.out.println(" h.t == " + h.t);System.out.println(" i == " + i);
}}
7/28/2019 04_EventHandling
32/49
95-712 OOP Java 32
public class LocalExample {
public static void main(String args[]) {
Top myObject = new Top();
}}
// OUTPUT
Constructing a Top objectBuilding a Wowh.t == 9i == 8
7/28/2019 04_EventHandling
33/49
95-712 OOP Java 33
An anonymous class is refinement of inner classes. It allows you to combine the definition of the class
with the instance allocation. Since it is instantiated in the same expression that defines
it, it can only be instantiated once. This is very similar tolocal classes. When writing a simple adapter class, the choice between
a named local class and an unnamed anonymous classtypically comes down to a matter of style and code clarity,rather than any difference in functionality.
The new class can't have a constructor.
Anonymous Classes
7/28/2019 04_EventHandling
34/49
95-712 OOP Java 34
// Anonymous.java
interface SmallClass {
public void foo();}
class Top {int i = 33;void someMethod(SmallClass s) {
s.foo();}void anotherMethod() {
someMethod(new SmallClass() {public void foo() {System.out.println("Really fun");}
});}
7/28/2019 04_EventHandling
35/49
95-712 OOP Java 35
Top() {System.out.println("Constructing a Top object");someMethod(new SmallClass() {
public void foo() {
System.out.println("Strange but fun");}});
}}
7/28/2019 04_EventHandling
36/49
95-712 OOP Java 36
public class Anonymous {
public static void main(String args[]) {
// We can't create interface objects// error: SmallClass s = new SmallClass();
Top myObject = new Top();myObject.anotherMethod();
}}// OUTPUTConstructing a Top objectStrange but funReally fun
7/28/2019 04_EventHandling
37/49
95-712 OOP Java 37
Event Handling Details
register Source Object Listener Object
fire events
After the listener object registers itself with the sourceobject, the source object calls a method found in thelistener object and passes an object that describes the event.
Event object
7/28/2019 04_EventHandling
38/49
95-712 OOP Java 38
Event Handling
Suppose we have a Button object Button b = new Button();
We must determine what events a particular component generates.
A Button component may generate an ActionEvent object.
Button b
ActionEventObject
7/28/2019 04_EventHandling
39/49
95-712 OOP Java 39
Implementing a Listener
class BabySitter implements ActionListener {
public void actionPerformed(ActionEvent e) {// handle the event object e in some way
}}
We need an object that will listen for the ActionEvent.We implement the ActionListener class (this class listens
for ActionEvents from buttons, menus, etc.) and override
its actionPerformed method.
7/28/2019 04_EventHandling
40/49
95-712 OOP Java 40
Create a BabySitter object
BabySitter sitter = new BabySitter();
sitter
7/28/2019 04_EventHandling
41/49
95-712 OOP Java 41
Registering The Listener
We want to listen for the ActionEventobject coming from the button.
So, we tell the button what object willlisten for the ActionEvent object:
b.addActionListener(sitter)
7/28/2019 04_EventHandling
42/49
95-712 OOP Java 42
The button and its listener
Button Object Sitter Object
The button calls the actionPerformed()method of the sitter objectand passes an ActionEvent objectas a parameter
addActionListener
7/28/2019 04_EventHandling
43/49
95-712 OOP Java 43
Hit the X and the program exits
Once again but with a window
7/28/2019 04_EventHandling
44/49
95-712 OOP Java 44
Create a WindowCloseSitter Class
import javax.swing.*;import java.awt.event.*;
public class CloseDemo {public static void main(String[] args) {
JFrame f = new JFrame("Example");f.setSize(400,100);
f.setVisible(true);WindowCloseSitter h = new WindowCloseSitter();f.addWindowListener(h);
}}
7/28/2019 04_EventHandling
45/49
95-712 OOP Java 45
class WindowCloseSitter implements WindowListener {
public void windowClosing(WindowEvent e) {System.exit(0);
}public void windowClosed(WindowEvent e) { }public void windowOpened(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }
public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }
}
But we have to implement ALL of the functions !!
7/28/2019 04_EventHandling
46/49
95-712 OOP Java 46
Java Provides Adapter Classes
ComponentAdapter MouseMotionAdapter
WidowAdapter ContainerAdapter MouseAdapter
FocusAdapter KeyAdapter
7/28/2019 04_EventHandling
47/49
95-712 OOP Java 47
The WindowAdapter class
public abstract class WindowAdapter implements WindowListener {
public void windowClosing(WindowEvent e) {}public void windowClosed(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }public void windowIconified(WindowEvent e) { }public void windowDeiconified(WindowEvent e) { }public void windowActivated(WindowEvent e) { }public void windowDeactivated(WindowEvent e) { }
}
A built in class -- we already have the empty bodies!!
7/28/2019 04_EventHandling
48/49
95-712 OOP Java 48
The Window again
import javax.swing.*;import java.awt.event.*;public class CloseDemo2 extends WindowAdapter {
public static void main(String[] args) {JFrame f = new JFrame("Example");f.setSize(400,100);f.setVisible(true);
f.addWindowListener(new CloseDemo2());}public void windowClosing(WindowEvent e) {
System.exit(0);}
}
7/28/2019 04_EventHandling
49/49
95-712 OOP Java 49
Again with anonymous classes
import javax.swing.*;import java.awt.event.*;public class CloseDemo3 {
public static void main(String[] args) {JFrame f = new JFrame("Example");f.setSize(400,100);f.setVisible(true);f.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
}); }