Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.

Slides:



Advertisements
Similar presentations
Event Handling.
Advertisements

Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 12 Event-Driven Programming 找出画中真谛 — 保罗. 塞尚.
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.
Mouse Events and Keyboard Events
Event Handling Events and Listeners Timers and Animation.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 15 Event-Driven Programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
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-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.
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.
3461 Sequential vs. Event-driven Programming Reacting to the user.
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.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
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.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
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.
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.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
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-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
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.
Event Listeners ActionListener –button,list AdjustmentListener-scroll bar ComponentListener-when component hidden…. ContainerListener-comp added or removed.
1 Chapter 3 Event-Driven Programming. 2 Objectives F To explain the concept of event-driven programming (§12.2). F To understand event, event source,
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.
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.
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.
EVENT HANDLING 10/8/2017.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
Chapter 14 Event-Driven Programming
Welcome To java
CompSci 230 S Programming Techniques
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
Lecture 09 Applets.
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Unit I: Chapter 1 Event handling.
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Making Java GUIs Functional
Presentation transcript:

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Chapter 13 Event Handling In Java

Objectives Understand event delegation model Understand what are events, sources, and listeners Know about their event classes and associated listeners how basic events are handled (in applets) learn three ways of event handling: Listeners, Adapters, and Inner classes

Introduction We have done enough of objects and classes by now. An object resides in a particular state until it is made to transit to other state. This transition occurs due to an event. For example, we want an object to invoke a function when an action is generated, e.g. pressing a key on the keyboard, moving the mouse, clicking on a button, etc. The object which generates the event, i.e. the source of the event is known as the event generator.

Introduction The object, responsible for performing the task when an event occurs is called the event handler. There may be more than one event handlers for one single event generated. How do these handlers know that a particular event has occurred so that they can perform their activity? There is a registration process, undertaken by the event object, for each of its event handlers. This registration involves the event handler simply asking the event generator to inform about the occurrence of an event. By registering, the event generator is able to keep track of all the registered event handlers.

Event Delegation Model In Event Delegation Model, a source generates events which are sent to one or more listeners. The listeners receive the event, and process them. The processing logic applied for handling an event is totally segregated by the logic that generates the event, i.e. the event-generating component can be designed differently than the event-processing component. Actually the event generating component delegates the responsibility of performing an event-based action to a separate event- performing component. The model has three dimensions, namely events, event sources and event listeners.

Event Delegation Model An event is an object that describes a state change in the source. It may be generated directly because of interaction with the components of GUI environment or any other reason such as expiry of timer, completion of an operation, etc. An event source is an object which generates the event. Generation of event must cause a change in the state of the source. A source can generate more than one event. Event Listeners are the objects that get notified when an event occurs on an event source.

java.awt.AWTEvent The java.awt.AWTEvent class is the root class for all AWT Events. java.awt.event packages includes the definition of events classes, listeners interfaces, and adapters classes, which from the basics for event handling.

Event classes Java has a predefined hierarchy of event- related classes, at the root of which is EventObject. It is actually a member of java.util package. This class has constructors and methods defined as its members. One such constructor is EventObject(Object src_obj) where, src_obj is the object, which generates the event. EventObject has methods like getSource() and toString(). getSource() – returns the source of the event toString() – returns the string equivalent of the event

Event Classes (contd.)

ActionEvent This event is generated by a component (such as a Button) when the component-specific action occurs (such as click). The event is passed to an ActionListener object which is registered to receive the event notification using the component’s addActionListener method. The object that inherits the ActionListener interface is passed to the ActionEvent when an event occurs. Some of the fields, constructors, and methods associated with the ActionEvent class

Field Summary of ActionEvent

Constructor of ActionEvent

Methods of ActionEvent

AdjustmentEvent The adjustment events are generated by Adjustable objects like scroll bar.

Fields of Adjustment Event

Constructor of AdjustmentEvent

Methods of AdjustmentEvent

KeyEvent KeyEvent is an event which indicates that a keystroke occurred in a component. public class KeyEvent extends InputEvent is generated by component object (such as a text field, Applet, Frame) when a key is pressed, released, or typed. The event is passed to a KeyListener object which is registered to receive the event notification using the component’s addKeyListener method. There can be three types of key events, which are identified by integer constants. KEY_PRESSED (it is generated when any key is pressed) KEY_TYPED (it is generated if a valid Unicode character could be generated) KEY_RELEASED (it is generated when any key is released)

Few Integers constants in KeyEvent

Constructor

Methods in KeyEvent

MouseEvent It is an event which indicates that a mouse action occurred in a component. A mouse action occurs in a particular component if and only if the mouse cursor is over the defined part of the component’s bounds when the action happens. public class MouseEvent extends InputEvent There are eight types of mouse events defined in the MouseEvent class. The MouseEvent class defines them as integer constants to identify each of these events.

Fields of MouseEvent

Constructors of MouseEvent

Methods of MouseEvent

FocusEvent This event is generated when a component gains or loses focus. There are two types of focus events: permanent and temporary. Permanent focus event occurs when the user explicitly changes focus from one component to other, e.g. by pressing tab key. Temporary focus event occurs when the focus is lost due to operations like Window deactivated. In this case, when the window will again be activated, the focus will be on same component.

Fields of FocusEvent

Constructor of FocusEvent

Methods of FocusEvent

ItemEvent It is an event which shows whether an item was selected or de-selected. public class ItemEvent extends AWTEvent This event is generated by an ItemSelectable object (such as a List), where the event is generated when an item of the list is either selected or de-selected. The event generated is passed to every ItemListener object which is registered to receive such events. The method addItemListener() is used for this registration process.

Fields of ItemEvent

ItemEvent (contd.)

TextEvent This event indicates the change in the object’s text. public class TextEvent extends AWTEvent This event is generated by an object (such as a TextComponent) whenever its text changes. The event is passed to every TextListener object which is registered to receive such events. The method addTextListener() is used for this registration process.

TextEvent (contd.)

Source of Events Button Choice MenuItem List Checkbox Window Scrollbar Text Components

Source of Events Event Listeners are created by implementing one or more interfaces defined by the java.awt.event package. Whenever a source generates an event, it basically invokes the appropriate method defined in the listener interface. The method has a event object passed as an argument to it.

Listeners

KeyListener This interface has three methods defined within it. void keyPressed(KeyEvent e) – invoked when a key is pressed void keyReleased(KeyEvent e) - invoked when a key is released void keyTyped(KeyEvent e) - invoked when a character is typed

MouseListener The interface has five methods, having the signatures as follows: void mouseClicked(MouseEvent e) void mouseEntered(MouseEvent e) void mousePressed(MouseEvent e) void mouseReleased(MouseEvent e) void mouseExited(MouseEvent e)

MouseMotionListener The interface has two methods having the signatures, void mouseMoved(MouseEvent e) void mouseDragged(MouseEvent e) mouseMoved() is invoked when the mouse is moved from one place to another and mouseDragged() is used when the mouse is dragged.

MouseWheelListener & ItemListener MouseWheelListener has only one method, having the signature, void mouseWheelmoved(MouseEvent e) - invoked when the mouse wheel is moved. ItemListener has only one method defined as, void itemStateChanged(ItemEvent e) - invoked when the state of the item changes.

ActionListener, TextListener & FocusListener ActionListener has only one method void actionPerformed(ActionEvent e) - invoked when any action event is performed. TextListener has only one method void textChanged(TextEvent e) - invoked whenever there is a change in text field or text area. FocusListener interface has two methods, void focusGained(FocusEvent e) - invoked when the component obtains keyboard focus and focusLost() void focusLost(FocusEvent e) - is invoked when the component looses the keyboard focus.

WindowListener This interface has seven methods void windowActivated(WindowEvent e) void windowClosed(WindowEvent e) void windowClosing(WindowEvent e) void windowOpened(WindowEvent e) void windowDeactivated(WindowEvent e) void windowIconified(WindowEvent e) void windowDeiconified(WindowEvent e)

Model Each source, generating the events must register event listeners to itself, so that listeners get the license for receiving the events from the respective source. Each type of event has its own registration method, having the form, public void addTypeListeners(TypeListener tl) These listeners, once registered for events from a particular source, can get unregistered also using public void removeTypeListener(TypeListerner tl) Once the listener objects are registered, they must implement the methods to receive and process the event notifications sent by source.

Example (MouseMotionListener) import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseMotionEx extends Applet implements MouseMotionListener { int xcord, ycord; public void init() { addMouseMotionListener(this); }

Continued public void paint(Graphics g) { g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,yc ord); } public void mouseMoved(MouseEvent me) { xcord = me.getX(); ycord = me.getY(); repaint(); public void mouseDragged(MouseEvent me){}

Another way of doing same /*<applet code = “MouseMotionEx.class” width = 700 height = 700 > </applet>*/ import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseMotionEx extends Applet { int xcord; int ycord; public void init(){ addMouseMotionListener (new Demo(this));} public void paint (Graphics g){ g.drawString (“(“+x cord +”, “+y cord+”)”); }} `

Another way of doing same (contd.) class Demo implements MouseMotionListener { MouseMotionEx m; Demo(MouseMotionEx m) this.m=m; } public void mouseMoved(MouseEvent me) { m.xcord = me.getX(); m.ycord = me.getY(); m.repaint();} public void mouseDragged(MouseEvent me) {}

Adapter classes In listener interfaces, you have to implement all the methods defined in that interface This can be annoying at times, particularly when you need to implement methods of the interface, which might not actually be used. In order to simplify things, Java came up with the concept of adapter classes. JDK defines corresponding adapter classes for listener interfaces containing more than one methods e.g. for MouseMotionListener, MouseMotionAdapter class has been defined. Adapter classes provide empty definitions for all the methods of their corresponding Listener interface. It means that MouseMotionAdapter class inherently implements MouseMotionListener interface.

Adapter classes

How to use Adapter classes? /*<applet code=”AdapterDemo.class” width=300 height=300></applet>*/ import java.awt.*; import java.awt.event.*; import java.applet.*; public class AdapterDemo extends Applet { int xcord,ycord; public void init(){ addMouseMotionListener(new MouseDemo(this)); } public void paint(Graphics g){ g.drawString(“(“+xcord+”,”+ycord+”)”,xcord,ycord ); }}

The Output

Inner classes Member classes An inner class can be defined and instantiated all inside a class, or even within an expression. member classes, local classes, and annoymous classes. Member classes are included in the class definition just like fields and methods. can either be static or instance. Static member class: A member class can be static with access only to the static members of the class to which it belongs. Instance member class: A member class can be instance with access to both the static and instance members of the class that contains it.

Inner classes (contd.) Local classes Anonymous Inner classes A local class is defined within a code block, typically in a method. An instance of a local class exists only during the execution of the method Anonymous Inner classes An anonymous inner class is one that is not assigned a name. Such classes are created on the fly i.e. they are created, instantiated, used and garbage collected when they are done. They are automatically assigned a name as Outerclassname$1. This anonymity helps in eliminating the unnecessary named objects. Besides, it makes the program more readable.

Use of Member Inner Class /*<applet code = OuterClass.class width=600 height=600> </applet>*/ import java.awt.*; import java.applet.*; import java.awt.event.*; public class OuterClass extends Applet { public void init() { addKeyListener(new InnerClass()); } class InnerClass extends KeyAdapter { public void keyPressed(KeyEvent ke) { showStatus(“key down”); } public void keyReleased(KeyEvent ke){ showStatus(“key up”); }}}

Use of Anonymous Inner Class /*<applet code=”AnonyKeyListDemo.class” width=300 height=300> </applet>*/ import java.awt.*; import java.awt.event.*; import java.applet.*; public class AnonyKeyListDemo extends Applet { public void init(){ addKeyListener(new KeyAdapter(){ public void keyPressed(KeyEvent ke){ showStatus(“Key Pressed”);} public void keyReleased(KeyEvent me){ showStatus(“Key Released”); } }); }}

The Output

Summary In this chapter, we have emphasized on the features that enhance the GUI capabilities of Java by using Event Handling. Event Handling model has been discussed. The modern approach to event handling uses Event Delegation Model where a source generates events, which are sent to one or more listeners. These Listeners receives the event notifications, which are handled as required by the different methods of event classes. All Three approaches for event handling have been discussed Listener interfaces Adapter classes Anonymous Inner classes