500 likes | 605 Views
Event Handling. Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications. Event Handling. Used by the Abstract Window Toolkit (AWT) – for basic GUI programming Java 1.0
E N D
Event Handling • Event Handling Overview • Listeners, Adapters and • Event Sources • Inner classes • Event Handling Details • Applets and GUI Applications 95-712 OOP Java
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 95-712 OOP Java
Babysitting A baby in the home needs attention. Many events surrounding the baby are not easily ignored. Events can be of different types. 95-712 OOP Java
One possible source of events 95-712 OOP Java
Babysitting Before responding to an event, a babysitter typically takes note of the source and the type of event. 95-712 OOP Java
Babysitting Handler Event type Event source The sitter needs to know both the event type and the event source. 95-712 OOP Java
Event Handling The window manager software may generate hundreds of different events. 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. 95-712 OOP Java
Events and Event Objects • Since events may be of different types but still exhibit some • shared traits (inheritance) Java represents the event classes • in a hierarchy. • The root class is called java.util.EventObject. The only common • feature shared by all events is a source object. So we find the • following method in the EventObject class : • public Object getSource(); 95-712 OOP Java
Object Some classes and methods in the event hierarchy. EventObject AWTEvent ActionEvent ComponentEvent String getActionCommand() WindowEvent InputEvent boolean isAltDown() Window getWindow() MouseEvent KeyEvent int getX() char getKeyChar() 95-712 OOP Java
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. 95-712 OOP Java
Example A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked Event data and methods Event Source Listener The listener object has methods that are called for particular events 95-712 OOP Java
Example A mouse object An event object that describes, say, the x and y coordinate of where the mouse was clicked Implements MouseListener A mouse object must be told who its listener is. The listener object has methods that are called for particular events The event object is sent to a listener method 95-712 OOP Java
The Listener • There are different types of Listeners. • MouseListeners • WindowListeners • ScrollBarListeners • Etc.. • These Listeners are interfaces. Remember what an interface • provides? If class X implements an interface then class X promises • to provide (at least) the methods declared in the interface. 95-712 OOP Java
Some of the Listener Hierarchy EventListener KeyListener ActionListener MouseListener abstract void actionPerformed(ActionEvent e); abstract void mouseClicked(MouseEvent e) 95-712 OOP Java
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? 95-712 OOP Java
An Example // MouseSpyApplet.java import java.applet.Applet; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; 95-712 OOP Java
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 provide ALL of these methods!! 95-712 OOP Java
public class MouseSpyApplet extends Applet { public MouseSpyApplet() { MouseSpy listener = new MouseSpy(); addMouseListener(listener); } } 95-712 OOP Java
Java Applets need an HTML file. <html> <head> </body> </head> <B>Spying on the mouse</b><p> <applet code="MouseSpyApplet.class" width=400 height=200> </applet> </html> 95-712 OOP Java
Another approach Suppose 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? 95-712 OOP Java
Only those methods that I am interested in. The other methods, when called, do nothing. We’ll visit this issue again later. 95-712 OOP Java
Inner Classes • Nested Top Level Classes (not inner) • Member Classes • Local Classes • Anonymous Classes 95-712 OOP Java
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 its • enclosing class. • It behaves just like a 'normal' class or interface. 95-712 OOP Java
//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"); } } 95-712 OOP Java
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 object Constructing SomeClass Hello 95-712 OOP Java
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 static • keyword and can access the members of each object of • its outer class. • The class 'appears in every instance'. 95-712 OOP Java
Member Classes (2) • The parent class must declare an instance of an inner class, before it can invoke the inner class methods, assign to data fields (including private ones), and so on. • Unlike nested top-level classes, inner classes are not directly part of a package and are not visible outside the class in which they are nested. • Inner classes are often used for GUI event handlers. 95-712 OOP Java
// MemberClassExample.java class 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); } } 95-712 OOP Java
public class MemberClassExample { public static void main(String args[]) { Top myObject = new Top(); } } // OUTPUT Constructing a Top object Constructing SomeClass 33 95-712 OOP Java
Local Classes • A local class is an inner class. Typically, a local class • is declared within a method. It is not a member of an • enclosing 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 object • could use a local class to define a simple implementation • of the ActionListener Interface. Then it could instantiate • this simple implementation and pass the resulting object • to the button's ActionListener method, thereby connecting • the button to the "callback" code that is executed when • the button is pressed. 95-712 OOP Java
// Local Class example class Top { int i = 33; Top() { System.out.println("Constructing a Top object"); // define a class within a method class 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); } } 95-712 OOP Java
public class LocalExample { public static void main(String args[]) { Top myObject = new Top(); } } // OUTPUT Constructing a Top object Building a Wow h.t == 9 i == 8 95-712 OOP Java
Anonymous Classes • 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 to • local classes. • When writing a simple adapter class, the choice between • a named local class and an unnamed anonymous class • typically comes down to a matter of style and code clarity, • rather than any difference in functionality. • The new class can't have a constructor. 95-712 OOP Java
// 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"); } }); } 95-712 OOP Java
Top() { System.out.println("Constructing a Top object"); someMethod(new SmallClass() { public void foo() { System.out.println("Strange but fun"); } }); } } 95-712 OOP Java
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(); } } // OUTPUT Constructing a Top object Strange but fun Really fun 95-712 OOP Java
Event Handling – Details register Source Object Listener Object Event object fire events After the listener object registers itself with the source object, the source object calls a method found in the listener object and passes an object that describes the event. 95-712 OOP Java
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 ActionEvent Object 95-712 OOP Java
Implementing a Listener • 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. class BabySitter implements ActionListener { public void actionPerformed(ActionEvent e) { // handle the event object e in some way } } 95-712 OOP Java
Create a BabySitter object BabySitter sitter = new BabySitter(); sitter 95-712 OOP Java
Registering The Listener • We want to listen for the ActionEvent object coming from the button. • So, we tell the button what object will listen for the ActionEvent object: • b.addActionListener(sitter) 95-712 OOP Java
The button and its listener addActionListener Button Object Sitter Object The button calls the actionPerformed() method of the sitter object and passes an ActionEvent object as a parameter 95-712 OOP Java
Once again but with a window Hit the X and the program exits 95-712 OOP Java
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); } } 95-712 OOP Java
But we have to implement ALL of the functions !! 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) { } } 95-712 OOP Java
Java Provides Adapter Classes • ComponentAdapter • MouseMotionAdapter • WidowAdapter • ContainerAdapter • MouseAdapter • FocusAdapter • KeyAdapter 95-712 OOP Java
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!! 95-712 OOP Java
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); } } 95-712 OOP Java
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); } } ); } } 95-712 OOP Java