Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Programming in Java; Instructor:John Punin Graphics and Graphical User Interfaces1 Programming in Java Graphics and Graphical User Interfaces.
TCU CoSc Programming with Java Handling Events.
Event Handling.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
Events and the AWT The objectives of this chapter are: To understand the principles of the Java 1.1 event model To understand how the event model is used.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
OOP&M - theory lectures1 OOP&M – the sixth day “… there must be a secret out there …” - Spok -
Event Handling Events and Listeners Timers and Animation.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
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.
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.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
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.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
– 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.
1 Unit 5 GUI Aum Amriteshwaryai Namah. 2 Overview Shall learn how to reuse the graphics classes provided by Java for constructing Graphical User Interface.
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.
CS102 – GUI AWT & Swing Components & Containers, Layout Managers, Events & Listeners MVC design pattern. David Davenport.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Computer Science [3] Java Programming II - Laboratory Course Lab 4: Common GUI Event Types and Listener Interfaces Layout Mangers Faculty of Engineering.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
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.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
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.
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,
Events in JAVA Needed for Applets and GUI based programs. Applet uses GUI to interact with user. Most of the events are generated by Mouse, Keyboard.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
Events (Chapter 11) Java Certification Study Group January 25, 1999 Mark Roth.
2/17/2016 DEPT OF CSE 1 EVENT HANDLING. 2/17/2016 DEPT OF CSE 2 Event handling is at the core of successful applet programming There are several types.
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.
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.
1 Lecture 8: User Interface Components with Swing.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUI Programming using Java - Event Handling
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
Welcome To java
CompSci 230 S Programming Techniques
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Aum Amriteshwaryai Namah
Handling User Events with Swing
Event Handling Chapter 2 Objectives
Java Events. Java Events Important definitions Overridden method Class vs. abstract class vs. interface Event Handling Definition Main components Windows.
Lecture 09 Applets.
Programming in Java Event Handling
CSE 114 – Computer Science I Event Programming
GUI Programming III: Events
Unit I: Chapter 1 Event handling.
Web Design & Development Lecture 12
Events, Event Handlers, and Threads
Making Java GUIs Functional
Presentation transcript:

Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA

10. EVENTS  Objectives  Interface Event  Event Delegation Model  The Event Class Hierarchy  Event Listeners  Explicit Event Enabling  Adapters

Objectives Write code to implement listener classes and methods, and in listener methods, extract information from the event to determine the affected component, mouse position, nature, and time of the event. State the event classname for any specified event listener interface in the java.awt.event package.

Interface Event When the user clicks a button, types text, uses the mouse, or performs any other interface-related action in your applet, an interface event occurs. When an event occurs, the applet is notified and takes the appropriate action.

Interface Event In GUI, the program responds to user events when they happen because the user directs the program flow by manipulating the controls in the applet. Java declares ActionListener as an interface to let you use the ActionListener methods. You can extend the Applet class to create your applet, and implement the ActionListener interface to use the Action- Listener methods as well.

Interface Event Most of the event classes reside in the java.awt.event package. The class that implements the ActionListener interface does not have to be the applet's main class. In fact, you can create an entirely new class, which helps break up the code.

Delegation Model Event Delegation Model Delegation-Based Event Model Listener Component

event delegation model a component may be told which object or objects should be notified when the component generates a particular kind of event If a component is not interested in an event type, then events of that type will not be propagated

The delegation model is based on four concepts: Event classes Event listeners Explicit event enabling Adapters

Delegation Model Event Delegation Model The delegation-based event model passes events from source controls to Listener objects. That means you will connect a Listener to your component. When an event occurs, the Listener object will hear it.

Delegation Model Event Delegation Model In this case, you will make the Listener object the applet object itself by connecting your applet to your component as a listener, using the button's addActionListener() method. To indicate that you want the applet itself to be the component's listener, you would need to be able to pass the applet as an argument to addActionListener(). public class clicker extends Applet implements ActionListener

Delegation Model Event Delegation Model That is accomplished with the this keyword, which refers to the current object. Then, when there are component events, they will be sent to your applet.

The Event Class Hierarchy Most of the event classes reside in the java.awt.event package

java.awt.AWTEvent java.util.eventobject The Event Class Hierarchy ActionEvent AdjustmentEventComponentEvent TextEvent ItemEvent ContainerEvent FocusEventInputEvent WindowEvent PaintEvent KeyEventMouseEvent

java.util.EventObject: topmost superclass of all the new event classes is. It is a very general class, with only one method of interest: Object getSource(): returns the object that originated the event One subclass of EventObject is java.awt.AWTEvent, which is the superclass of all the delegation model event classes. Again, there is only one method of interest: int getlD(): returns the ID of the event

An event's ID is an int that specifies the exact nature of the event. For example, an instance of the MouseEvent class can represent one of seven occurrences: a click, a drag, an entrance, an exit, a move, a press, or a release Each of these possibilities is represented by an int: MouseEvent.MOUSE_CLICKED, MouseEvent.MOUSE_DRAGGED, and so on.

Subclasses of java.awt.AWTEvent event types that can be generated by the various AWT components ActionEvent: generated by activation of components AdjustmentEvent: generated by adjustment of adjustable component such as scroll bars ContainerEvent: generated when components are added to or removed from a container

FocusEvent: generated when a component receives or loses input focus ItemEvent: generated when an item is selected from a list, choice, or check box KeyEvent: generated by keyboard activity MouseEvent: generated by mouse activity

PaintEvent: generated when a component is painted TextEvent: generated when a text component is modified WindowEvent: generated by window activity (such as iconifying or de-iconifying)

The InputEvent superclass has a getWhen() method that returns the time when the event took place; the return type is long The MouseEvent class has getX() and getY() methods that return the position of the mouse within the originating component at the time the event took place; the return types are both int

Event Listeners An event listener is an object to which a component has delegated the task of handling a particular kind of event

When the component experiences input, an event of the appropriate type is constructed; the event is then passed as the parameter to a method call on the listener A listener must implement the interface that contains the event-handling method Example: a button in an applet When the button is clicked, an action event is to be sent to an instance of class MyActionListener

1. class MyActionListener implements ActionListener { 2. public void actionPerformed( ActionEvent ae ) { 3. System.out.println( "Action performed." ); 4. } 5. }

1. public class ListenerTest extends Applet { public void init() { Button btn = new Button( "OK" ); MyActionListener listener = new MyActionListener(); 5. btn.addActionListener( listener ); 6. add( btn ); 7. } 8. }

import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class click extends Applet implements ActionListener { TextField texto; Button boton; public void init() { texto = new TextField(20); add(texto); texto.setText("Bienvenido a Java"); boton = new Button("Haga Click!"); add(boton); boton.addActionListener(this); }

public void actionPerformed(ActionEvent event) { String msg = new String("Welcome to Java"); if(event.getSource() == boton) { texto.setText(msg); }

A standard formula for giving an action listener to a component 1. 1.Create a listener class that implements the ActionListener interface 2. Construct the component 3. Construct an instance of the listener class 4. Call addActionListener() on the component, passing in the listener object

A component may have multiple listeners for any event type There is no guarantee that listeners will be notified in the order in which they were added There is also no guarantee that all listener notification will occur in the same thread; thus listeners must take precautions against corrupting shared data

Listener Interfaces InterfaceInterface methodsAdd Method ActionListeneractionPerformed( ActionEvent )addActionListener() AdjustmentListeneradjustmentValueChanged( AdjustmentEvent ) addAdjustmentListener() ComponentListenercomponentHidden( ComponentEvent ) componentMoved( ComponentEvent ) componentResized( ComponentEvent ) componentShown( ComponentEvent ) addComponentlistener() ContainerListenercomponentAdded( ContainerEvent ) componentRemoved( ContainerEvent ) addContainerListener() FocusListenerfocusGained( FocusEvent ) focusLost( FocusEvent ) addFocusListener()

Listener Interfaces... InterfaceInterface methodsAdd Method ItemListeneritemStateChanged( ItemEvent )addItemListener() KeyListenerkeyPressed( KeyEvent ) keyReleased( KeyEvent ) keyTyped( KeyEvent ) addKeyListener() MouseListenermousedClicked( MouseEvent ) mouseEntered( MouseEvent ) mouseExited( MouseEvent ) mousePressed( MouseEvent ) mouseReleased( MouseEvent ) addMouseListener() MouseMotionListenermouseDragged( MouseEvent ) mouseMoved( MouseEvent ) addMouseMotionListener()

Listener Interfaces... InterfaceInterface methodsAdd Method TextListenertextValueChanged( TextEvent )addTextListener() WindowListenerwindowActivated( WindowEvent ) windowClosed( WindowEvent ) windowClosing( WindowEvent ) windowDeactivated( WindowEvent ) windowDeiconified( WindowEvent ) windowlconified( WindowEvent ) windowOpened( WindowEvent ) addWindowListener()

An event listener may be removed from a component's list of listeners by calling a removeXXXListener() method, passing in the listener to be removed btn.removeActionListener( al );

Explicit Event Enabling There is an alternative to delegating a component's events It is possible to subclass the component and override the method that receives events and dispatches them to listeners Example: components that originate action events have a method called processActionEvent( ActionEvent ), which dispatches its action event to each action listener

1. class MyBtn extends Button { 2. public MyBtn( String label ) { 3. super( label ); 4. enableEvents( AWTEvent.ACTION_EVENT_MASK ); 5. } public void processActionEvent( ActionEvent ae ) { 8. System.out.println( "Processing an action event." ); 9. super.processActionEvent( ae ); 10. } 11. }

1. 1.class MyBtn extends Button implements ActionListener { 2. public MyBtn( String label ) { 3. super( label ); addActionListener( this ); } public void actionPerformed( ActionEvent ae ) { // Handle the event here } } you can always make a component subclass handle its own events by making the subclass an event listener of itself

The only difference between this strategy and the enableEvents() strategy is the order in which event handlers are invoked When you explicitly call enableEvents(), the component's processActionEvent() method will be called before any action listeners are notified When the component subclass is its own event listener, there is no guarantee as to order of notification

Event Masks Each of the 11 listener types has a corresponding XXX_EVENT_MASK constant defined in the AWTEvent class, and corresponding processXXXEvent() methods

Event Masks MaskMethod AWTEvent.ACTION EVENT MASKprocessActionEvent() AWTEvent.ADJUSTMENT EVENT MASKprocessAdjustmentEvent() AWTEvent.COMPONENT EVENT MASKprocessComponentEvent() AWTEvent.CONTAINER EVENT MASKprocessContainerEvent() AWTEvent.FOCUS EVENT MASKprocess FocusEvent() AWTEvent.ITEM EVENT MASKprocessItemEvent() AWTEvent.KEY_EVENT_MASKprocessKeyEvent() AWTEvent.MOUSE_EVENT_MASKprocessMouseEvent() AWTEvent.MOUSE_MOTION_EVENT_MASKprocessMouseMotionEvent() AWTEvent.TEXT_EVENT_MASK AWTprocessTextEvent() Event.WINDOW EVENT MASKprocessWindowEvent()

The strategy of explicitly enabling events for a component: Create a subclass of the component 2. 2.In the subclass constructor, call enableEvents( AWTEvent.XXXEVENT_MASK ) 3. 3.Provide the subclass with a processXXXEvent() method; this method should call the superclass' version before returning

Example: Catching iconified events on a frame Adapters 1. 1.class MyIkeListener implements WindowListener { 2. public void windowIconified( WindowEvent we ) { 3. // process the event 4. } 5. }

1. class MylkeListener extends WindowAdapter { 2. public void windowIconified( WindowEvent we ) { 3. // process the event 4. } 5. } The java.awt.event provides seven adapter classes, one for each listener interface that defines more than just a single method An adapter is simply a class that implements an interface by providing do-nothing methods

Adapter Class Listener Interface Adapter Class Listener Interface___________________________________________________________ ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapterFocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapterWindowlistener Adapters