Programming in Java Event Handling

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

Event Handling.
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.
For IST410 Students only Events-1 Event Handling.
Event-Driven Programming
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.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 16 Event-Driven Programming.
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.
1 Event-Driven Programming Just like designing GUIs, you also will probably not write Java code like the program examples given in these notes. You will.
Io package as Java’s basic I/O system continue’d.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
1 CSE 331 More Events (Mouse, Keyboard, Window, Focus, Change, Document...) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D.
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.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
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.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 12 Event-Driven Programming.
Pravin Yannawar, DOCS, NMU Jalgaon. Basic Java : Event handling in AWT and Swing 2 Objectives of This Session Explain the Event handling mechanism & demonstrate.
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.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
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.
Creating User Interfaces Event-Driven Programming.
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.
EVENT-DRIVEN PROGRAMMING Subject:T0934 / Multimedia Programming Foundation Session:2 Tahun:2009 Versi:1/0.
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.
Chapter 5: Enhancing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
GUI Programming using Java - Event Handling
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.
Applets.
Chapter 12 Event-Driven Programming
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Responding to Events Event Handling in Java
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Introduction to Event Handling
Chapter 16 Event-Driven Programming
Constructors, GUI’s(Using Swing) and ActionListner
ITEC220 GUI Lecture – Part 2 References
Presentation transcript:

Programming in Java Event Handling Lovely Professional University, Punjab

Outlines Delegation Event Model ActionListener ItemListener KeyListener MouseListener MouseMotionListener

Introduction An event can be defined as a signal to the program that something has happened. Events are triggered either by external user actions, such as mouse movements, button clicks, and keystrokes, or by internal program activities, such as a timer. The program can choose to respond to or ignore an event. The component that creates an event and fires it is called the source object or source component. For example, a button is the source object for a button-clicking action event.

Introduction An event is an instance of an event class. The root class of the event classes is java.util.EventObject. We can identify the source object of an event using the getSource() method in the EventObject class. The subclasses of EventObject deal with special types of events, such as action events, window events, component events, mouse events, and key events.

Delegation Event Model

The Delegation Event Model The delegation event model defines standard and consistent mechanisms to generate and process events. Principle: A source generates an event and sends it to one or more listeners. The listener waits until it receives an event. Once an event is received, the listener processes the event and then returns. Advantage: The application logic that processes events is cleanly separated from the user interface logic that generates those events. A user interface element is able to “delegate” the processing of an event to a separate piece of code.

In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them.

Event An event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. For Example, pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed.

public void addTypeListener(TypeListener el) Event Source An Event source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. public void addTypeListener(TypeListener el)

When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as multicasting the event. In all cases, notifications are sent only to listeners that register to receive them. Some sources may allow only one listener to register. public void addTypeListener(TypeListener el) throws java.util.TooManyListenersException

Event Listener A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved.

Listener Interfaces

Listener API Table Listener Interface Listener Methods ActionListener actionPerformed(ActionEvent) ItemListener itemStateChanged(ItemEvent) MouseListener mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) MouseMotionListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent)

ActionListener Action listeners are most common event handlers to implement. An action event occurs, whenever an action is performed by the user. We implement an action listener to define what should be done when an user performs certain operation. Examples: When the user clicks a button, chooses a menu item, presses Enter in a text field. The result is that an actionPerformed message is sent to all action listeners that are registered on the relevant component.

To write an Action Listener, follow the steps given below: Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example: public class MyClass implements ActionListener { Register an instance of the event handler class as a listener on one or more components. someComponent.addActionListener(instanceOfMyClass); Include code that implements the methods in listener interface. public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

ActionEvent Class Method Purpose String getActionCommand() Returns the string associated with this action. Most objects that can fire action events support a method called setActionCommand that lets you set this string. int getModifiers() Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the ActionEvent-defined constants SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed. Object getSource() Returns the object that fired the event.

ItemListener Interface Item events are fired by components that implement the ItemSelectable interface. Generally, ItemSelectable components maintain on/off state for one or more items. The Swing components that fire item events include buttons like check boxes, check menu items, toggle buttons and combo boxes etc. ItemListener Interface has only one method. public void itemStateChanged (ItemEvent)

ItemEvent class Method Purpose Object getItem() Returns the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item. ItemSelectable getItemSelectable() Returns the component that fired the item event. You can use this instead of the getSource method. int getStateChange() Returns the new state of the item. The ItemEvent class defines two states: SELECTED and DESELECTED.

KeyListener Interface Key events indicate when the user is typing at the keyboard. Key events are fired by the component with the keyboard focus when the user presses or releases keyboard keys. Notifications are sent about two basic kinds of key events: The typing of a Unicode character The pressing or releasing of a key on the keyboard

The first kind of event is called a key-typed event. To know when the user types a Unicode character ? whether by pressing one key such as 'a' or by pressing several keys in sequence ? The second kind is either a key-pressed or key-released event. To know when the user presses the F1 key, or whether the user pressed the '3' key on the number pad, you handle key-pressed events.

Methods of KeyListener Interface Purpose keyTyped(KeyEvent) Called just after the user types a Unicode character into the listened-to component. keyPressed(KeyEvent) Called just after the user presses a key while the listened-to component has the focus. keyReleased(KeyEvent) Called just after the user releases a key while the listened-to component has the focus.

boolean isActionKey() KeyEvent class Method Purpose int getKeyChar() Obtains the Unicode character associated with this event. int getKeyCode() Obtains the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the Escape key. boolean isActionKey() Returns true if the key firing the event is an action key. Examples of action keys include Cut, Copy, Paste, Page Up, Caps Lock, the arrow and function keys.

MouseListener Interface Mouse events notify when the user uses the mouse (or similar input device) to interact with a component. Mouse events occur when the cursor enters or exits a component's onscreen area and when the user presses or releases one of the mouse buttons.

Methods of MouseListener Interface Purpose mouseClicked(MouseEvent) Called just after the user clicks the listened-to component. mouseEntered(MouseEvent) Called just after the cursor enters the bounds of the listened-to component. mouseExited(MouseEvent) Called just after the cursor exits the bounds of the listened-to component. mousePressed(MouseEvent) Called just after the user presses a mouse button while the cursor is over the listened-to component. mouseReleased(MouseEvent) Called just after the user releases a mouse button after a mouse press over the listened-to component.

MouseEvent class Method Purpose int getClickCount() int getButton() Returns the number of quick, consecutive clicks the user has made (including this event). For example, returns 2 for a double click. int getButton() Returns which mouse button, if any, has a changed state. One of the following constants is returned: NOBUTTON, BUTTON1, BUTTON2, or BUTTON3. int getX() int getY() Return the (x,y) position at which the event occurred, relative to the component that fired the event.

MouseAdapter Class MouseAdapter class provides an empty implementation of all the methods in MouseListener interface. This class exists as convenience for creating listener objects. Extend this class to create a MouseEvent listener and override the methods for the events of interest. Create a listener object using the extended class and then register it with a component using the component's addMouseListener method. When a mouse button is pressed, released, or clicked (pressed and released), or when the mouse cursor enters or exits the component, the relevant method in the listener object is invoked and the MouseEvent is passed to it.

MouseMotionListener Interface Mouse-motion events notify when the user uses the mouse (or a similar input device) to move the onscreen cursor. If an application requires the detection of both mouse events and mouse-motion events, use the MouseInputAdapter class. It implements the MouseInputListener a convenient interface that implements both the MouseListener and MouseMotionListener interfaces.

Methods of MouseMotionListener Interface Purpose mouseDragged(MouseEvent) Called in response to the user moving the mouse while holding a mouse button down. This event is fired by the component that fired the most recent mouse-pressed event, even if the cursor is no longer over that component. mouseMoved(MouseEvent) Called in response to the user moving the mouse with no mouse buttons pressed. This event is fired by the component that's currently under the cursor.