47
What Is an Event? • Events – Objects that describe what happened • Event sources – The generator of an event • Event handlers – A method that receives an event object, deciphers it, and processes the user’s interaction

What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Embed Size (px)

DESCRIPTION

Sources: –The mouse and keyboard and the GUI components (Buttons, lists, checkboxes etc.) Events: –Objects that describe a state change in a source. Listeners: –Objects notified when events occur.

Citation preview

Page 1: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

What Is an Event?• Events – Objects that describe what

happened• Event sources – The generator of an

event• Event handlers – A method that

receives an eventobject, deciphers it, and processes the

user’s interaction

Page 2: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Delegation model

Page 3: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

•Sources:–The mouse and keyboard and the GUI components (Buttons, lists, checkboxes etc.)

•Events:–Objects that describe a state change in a source.

•Listeners:–Objects notified when events occur.

Page 4: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Source

Event Object

Listener

When the state of the source changes…

The Source registers a Listener…

The Source generates an event and sends it to the registered listener

Page 5: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Any number of event listener objects can listen for all kinds of events from any number of event source objects.

E.g. a program might create one listener per event source. Or a program might have a single listener for all events

from all sources.

Listeners

Page 6: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Listeners

Multiple listeners can register to be notified of events of a particular type from a particular source.

Also, the same listener can listen to notifications from different objects.

Each type of listeners can be notified only for its corresponding types of events which can be generated by specific types of sources.

Page 7: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Multiple sources, single listenerMany buttons can register the same

listener since all buttons generate the same type of event. This type of event may be generated by other types of sources as well.

button1

ListItem3

button2

ActionListener

Action

Event3ActionEvent2ActionEvent1

Action

Event3

Page 8: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Single source, multiple listeners

A single source may generate different types of events and thus register multiple listeners.

MouseMotion Listener

MouseWheel Listener

MouseEvent

MouseWheelEvent Mouse

Page 9: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Listeners as interfaces

You implement an interface to create a listener.In the case of a single source that generates multiple

types of events you can create a single listener that implements all interfaces (remember: a class may extend only one superclass but implement more than one interfaces).

Page 10: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Delegation Model

import java.awt.*;

public class TestButton {

public static void main(String args[]) {

Frame f = new Frame("Test");

Button b = new Button("Press Me!");

b.addActionListener(new ButtonHandler());

f.add(b,BorderLayout.CENTER);

f.pack(); f.setVisible(true);}}

import java.awt.event.*;

public class ButtonHandler implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("Action occurred");

System.out.println(7 "Button's label is :" + e.getActionCommand()); }

Page 11: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

FrameWith a Single Button1 import java.awt.*;

2

3 public class TestButton {

4 public static void main(String args[]) {

5 Frame f = new Frame("Test");

6 Button b = new Button("Press Me!");

7 b.addActionListener(new ButtonHandler());

8 f.add(b,BorderLayout.CENTER);

9 f.pack();

10 f.setVisible(true);

11 }

12 }

Page 12: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

The ButtonHandlerClass1 import java.awt.event.*;

2

3 public class ButtonHandler implements ActionListener {

4 public void actionPerformed(ActionEvent e) {

5 System.out.println("Action occurred");

6 System.out.println(

7 "Button's label is :" + e.getActionCommand());

8 }

9 }

Page 13: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event-Handling in Java• An object that describes a change of state in a source

component is called an event. • The source components can be the elements of the Graphical

User Interface (GUI). • Events are supported by the classes and interfaces defined in

the java.awt.event package. • Identifying the Source Of Events:

•An event source is an object that generates an event. •An event source registers some listeners, which receive

notifications about a specific type of event generated by that particular event source.

•All the registered listeners are notified about the generation of an event and receive a copy of the event object.

•This is known as multicasting the event. •Some sources allow only single listener to register. •This is known as unicasting of event.

Page 14: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

• Various event sources and the types of events they generate:

Event Source Description

Checkbox Creates an item event when a check box is selected or deselected.

Button Creates an action event when a button is pressed.

List Creates an action event when an item is double-clicked; creates an item event when an item is selected or deselected.

Page 15: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Source Description

Scrollbar Creates an adjustment event when a scroll bar is scrolled.

Text components Creates a text event when a text character is entered in the text component.

Window Creates a window event when a window is activated, deactivated, opened, closed, or quit.

Page 16: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Listeners and Event Handlers•An event listener listens for a specific event and is

notified when that specific event occurs.•An event listener registers with one or more event

sources to receive notifications about specific types of events and processes the events.

•An event-handler is called by the event listener whenever a specific event occurs.

•Event listeners are interfaces and the event-handler is a method declared in the event listener interface that is implemented by the application.

•The syntax of a method that registers an event listener with an event source is: public void addTYPEListener(TYPEListener obj)

Page 17: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

•The Delegation Event Model•The delegation event model is based on the concept

that source generates the event and notifies one or more event listeners.

•The delegation event model allows you to specify the objects that are to be notified when a specific event occurs.

•In delegation event model, the event listener has to be registered with a source in order to get notified about the occurrence of a particular event.

Page 18: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes• The Java event class hierarchy:

Page 19: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes• The Action Event class

•ActionEvent is generated by an AWT component, such as a button, when a component-specific action is performed.

•The action event is generated when a button is pressed, a list item is double-clicked, or a menu item is selected.

•The following syntax shows the declaration of the constructor of the ActionEvent class is:

public ActionEvent(Object source, int id, String command)

•The main methods included in the Action Event class are: •String getActionCommand() •int getModifiers()

Page 20: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes The MouseEvent class

• The MouseEvent class extends the java.awt.event.InputEvent class.

• The mouse event indicates that a mouse action has occurred on a component.

• The mouse events include: • Pressing a mouse button• Releasing a mouse button• Clicking a mouse button• Entering of mouse in a component area• Exiting of mouse from a component area

• The mouse event class defines some integer constants that can be used to identify several types of mouse events.

Page 21: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes

• Various integer constants of the Event class:

Constants Description

MOUSE_CLICKED Identifies the event of mouse clicking.

MOUSE_DRAGGED Identifies the event of dragging of mouse.

MOUSE_MOVED Identifies the event of mouse moving.

MOUSE_PRESSED Identifies the event of mouse pressing.

Page 22: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes

Constants Description

MOUSE_RELEASED Identifies the event of mouse releasing.

MOUSE_ENTERED Identifies the event of mouse entering an AWT component.

MOUSE_EXITED Identifies the event of mouse exiting an AWT component.

 

Page 23: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Classes•The following syntax shows the declaration of one of the

constructors of the MouseEvent class: public MouseEvent(Component source, int eventType,

long when, int modifiers, int x, int y, int clickCount, boolean triggersPopup )

•Various methods of the MouseEvent class:

Methods Description

public int getX() Returns the horizontal x coordinate of the mouse position relative to a source component.

public int getY() Returns the vertical y coordinate of the mouse position relative to a source component.

Page 24: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event ClassesMethods Description

public point getPoint() Returns the Point object. The Point object contains the x and y coordinates of the mouse position relative to a source component.

public void translatePoint(int x, int y)

Translates the coordinates of a mouse event to a new position by adding x and y offsets.

public int getClickCount() Returns the number of mouse clicks associated with an event.

Page 25: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Listener Interfaces• An event listener registers with an event source to receive

notifications about the events of a particular type. • Various event listener interfaces defined in the

java.awt.event package:Interface Description

ActionListener Defines the actionPerformed() method to receive and process action events.

MouseListener Defines five methods to receive mouse events, such as when a mouse is clicked, pressed, released, enters, or exits a component.

MouseMotionListener Defines two methods to receive events, such as when a mouse is dragged or moved.

Page 26: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Listener InterfacesInterface Description

AdjustmentListner Defines the adjustmentValueChanged() method to receive and process the adjustment events.

TextListener Defines the textValueChanged() method to receive and process an event when the text value changes.

WindowListener Defines seven window methods to receive events.

ItemListener Defines the itemStateChanged() method when an item has been selected or deselected by the user.

Page 27: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Example-Using the ActionListener Interface• Problem Statement

Create an applet that contains a button. When you click the button,

the label of the button is changed from "Click here" to "Button

clicked". • Solution

• To solve the above problem, perform the following tasks:• Code the application• Compile and execute the application

Page 28: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using the MouseListener Interface• The MouseListener interface is implemented for receiving

various mouse events, such as when you press, click, release, enter, and exit a component.

• Various public methods declared in the MouseListener interface:

Methods Description

void mouseClicked(MouseEvent me) Performs an action when the mouse button clicks a component.

void mousePressed(MouseEvent me) Performs an action when mouse button presses a component.

void mouseReleased(MouseEvent me)

Performs an action when the mouse button releases a component.

void mouseEntered(MouseEvent me) Performs an action when a mouse enters a component area.

void mouseExited(MouseEvent me) Performs an action when a mouse exits a component area.

Page 29: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Adapter Classes• The Java programming language provides adapter classes,

which implement the event listener interfaces containing more than one event-handling method.

• An adapter class provides an empty implementation of the event-handling methods in an event listener interface.

• The adapter classes are useful because they allows you to receive and process only some of the events that are handled by a particular event listener interface.

• You can define a class that acts as an event listener by extending one of the adapter classes and overriding its methods to handle a particular type of event.

Page 30: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Adapter Classes Various adapter classes:

Adapter Class Description

KeyAdapter Provides empty implementation of the methods of the KeyListener interface.

MouseAdapter Provides empty implementation of the methods of the MouseListener interface.

MouseMotionAdapter Provides empty implementation of the methods of the MouseMotionListener interface.

Page 31: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

• Various adapter classes: (contd.)

Adapter Classes

Adapter Class Description

WindowAdapter Provides empty implementation of the methods of the WindowListener and WindowFocusListener interfaces.

FocusAdapter Provides empty implementation of the methods of the FocusListener interface.

Page 32: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Adapter Classes• Using the MouseAdapter Class

• The MouseAdapter class provides empty implementation of mouse event-handling methods, such as mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and mouseReleased().

• A class that acts as a listener for mouse events extends the MouseAdapter class and overrides the required methods.

•Using the MouseMotionAdapter Class

• The MouseMotionAdpater class provides empty implementation of methods, such as mouseDragged() and mouseMoved().

• A class that acts as a listener for mouse motion events extends the MouseAdapter class and overrides the required method.

Page 33: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

• The components of an event-driven program are:• Event Source: Refers to AWT components such as

Button, List, Checkbox, and Scrollbar that generate events.

• Event Listener- Refers to any object that receives messages or events.

• Event Handler- Refers to the method that receives and processes the event. The event handler method takes an Event object as a parameter.

• The various event classes in Java, such as the ActionEvent and MouseEvent classes.

• To handle action events, you need to register the listener object that implements the ActionListener interface.

• To handle mouse events, you need to register the listener object that implements the MouseListener interface.

• Events generated by mouse are of two types, mouse events and mouse motion events.

Page 34: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

• Mouse events include, pressing a mouse button, releasing a mouse button, clicking a mouse button, entering of a mouse in a component area, exiting of a mouse from a component area.

• Mouse motion events include, moving a mouse and dragging a mouse.

• Adapter classes provides an empty implementation of all the methods in an event listener interface.

Page 35: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Event Handling

• When an event is generated by a source it is handled by the listener registered by this source.

• As shown, the listener is an implemented interface (or an extended adapter) and thus you have to implement some methods.

• These methods take the event as an argument and this is where you put the code to be executed when the event happens.

• In other words, you define what you want to happen eg. when a button is pressed, inside the actionPerformed method implemented inside the listener

• To be able to do that efficiently, the event classes define specific methods to extract information about the events.

Page 36: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

EventObject:// superclass of all events, so the following method is inherited by all event objectsObject getSource()

MouseEvent:int getX(), int getY()int getButton()

KeyEvent:char getKeyChar()

ActionEvent:String getActionCommand()long getWhen()

Event Handling

Page 37: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Four design options

Implement your handlers:in separate classes,using inner classesusing anonymous inner classes,in the same class that creates your window.

Page 38: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using inner classes

This is the easiest and more practical approach.Inner classes belong to the app class and have

access to all its members.The only thing you have to do is implement the

handler and add its object to the element.

Page 39: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using inner classes//Declare your handler class:class MyHandler Implements ActionListener{ ...

//Add the actionPerformed method inside your handler class:public void actionPerformed(ActionEvent ev){...

// Inside your app’s constructor, create your element objects:

b1=new JButton(“I’m a Swing button!”); ...

// Inside your app’ s constructor, add them on your content pane:

myCont.add(b1); ...

// Tie them together in two steps:// Create a handler object inside the app’s constructor:MyHandler handler = new MyHandler();// Add it to the element:b1.addActionListener(handler);

Page 40: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using anonymous inner classes

This is a variation of the previous option.An anonymous inner class is an inner class

without a name.You define the class “on the fly” when you

need an instance of it (an object) to be created.

Page 41: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using anonymous inner classes

//Inside the app’s constructor where you have added the component on the content pane, add the listener just as in the previous case. Only this time write its code at the same time you instantiate and add it:

b1.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ev) {...

Page 42: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using a separate class

Since this does not belong to the app class, it cannot access its private members directly.

Due to the above you need to implement public access methods for each app’s element in order to be able to interact with them through the handler.

Page 43: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Apart from the above you need to pass a reference of your app object to the handler in order to tie the app and the handler together.

Using an inner class you didn’t have to do this, since the handler class belong to the app itself.

How you do this:

Using a separate class

Page 44: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using a separate class// Create a handler object inside the app’s constructor. Pass a

reference to the app using this as an argument:MyHandler handler = new MyHandler(this);// Add it to the element (as with the inner classes):b1.addActionListener(handler);

// Inside the handler class:// Declare an app object:MyApp appObj;// Create a handler’s constructor which takes an app object as an

argument. This is the app object that ties the app with the handler. Assign this object to the object declared inside your handler’s class.

public MyHandler (MyApp app){ appObj=app;}

Page 45: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using a separate class// Inside the handler class:// Add the actionPerformed method (as previously) and access all elements through

the appObj:public void actionPerformed(ActionEvent ev){if ev.getSource()==appObJ.b1{......

Page 46: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using the same class

You can make the class that extends a JFrame (the app class) to listen to its own events. This way you have all access advantages you had by using inner classes and putting everything together is easy as well.

Page 47: What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event

Using the same class

//Extend a JFrame and implement a handler at the same time. actionPerformed is now a method of this same class:

class MyHandler extends JFrame implements ActionListener{ ...

//Inside the app’s constructor, register the listener by using this, as the handler-adding methods need handler objects to be passed as arguments. In this case the object passed is of the very same class:

b1.addActionListener(this);