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.

Slides:



Advertisements
Similar presentations
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Advertisements

Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Event Handling.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
For IST410 Students only Events-1 Event Handling.
Event-Driven Programming
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications Event.
1 Gui Programming (Part I) Graphical User Interfaces (Part I) l Introduction to events. l A Brief history. l Event sources and listeners. l The delegation.
Intermediate Java1 An example that uses inner classes Week Four Continued.
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Graphical User Interface Components: Part 1 Chapter 11.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
For (int i = 1; i
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
UID – Event Handling and Listeners Boriana Koleva
Event Handling. 2 GUIs are event driven –Generate events when user interacts with GUI e.g., moving mouse, pressing button, typing in text field, etc.
Interactive Programs Java API. Terminology Event—an action or occurrence, not part of a program, detected by the program. Events can be Event—an action.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
Object Oriented Programming.  Interface  Event Handling.
Event Handling. The signals that a program receives from the operating system as a result of the actions are called events. A window based program is.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Event Handling and Listeners in SWING The practice of event handling.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Dept. of CSIE, National University of Tainan 10/21/2012 Responding to User Input.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
A First Look at GUI Applications
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Making Java GUIs Functional
Presentation transcript:

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

Delegation model

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.

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

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

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.

Multiple sources, single listener Many 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 ActionEvent3 ActionEvent2 ActionEvent1 ActionEvent3

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

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).

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()); }

FrameWith a Single Button 1 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 }

The ButtonHandler Class 1 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 }

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.

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.

Event SourceDescription 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.

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)

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.

Event Classes The Java event class hierarchy:

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()

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.

Event Classes Various integer constants of the Event class: Constants Description MOUSE_CLICKED Identifies the event of mouse clicking. MOUSE_DRAGGEDIdentifies the event of dragging of mouse. MOUSE_MOVEDIdentifies the event of mouse moving. MOUSE_PRESSEDIdentifies the event of mouse pressing.

Event Classes Constants Description MOUSE_RELEASEDIdentifies the event of mouse releasing. MOUSE_ENTEREDIdentifies the event of mouse entering an AWT component. MOUSE_EXITEDIdentifies the event of mouse exiting an AWT component.

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: MethodsDescription 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.

Event Classes Methods 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.

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: InterfaceDescription ActionListenerDefines the actionPerformed() method to receive and process action events. MouseListenerDefines 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.

Event Listener Interfaces InterfaceDescription AdjustmentListner Defines the adjustmentValueChanged() method to receive and process the adjustment events. TextListenerDefines 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.

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

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: MethodsDescription 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.

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.

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.

Various adapter classes: (contd.) Adapter Classes Adapter Class Description WindowAdapter Provides empty implementation of the methods of the WindowListener and WindowFocusListener interfaces. FocusAdapterProvides empty implementation of the methods of the FocusListener interface.

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.

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.

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.

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.

EventObject: // superclass of all events, so the following method is inherited by all event objects Object getSource() MouseEvent: int getX(), int getY() int getButton() KeyEvent: char getKeyChar() ActionEvent: String getActionCommand() long getWhen() Event Handling

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

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.

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);

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.

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) {...

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.

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

// 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;}

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{......

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.

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);