For IST410 Students only Events-1 Event Handling.

Slides:



Advertisements
Similar presentations
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Advertisements

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.
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.
Unit 111 Event-Driven Programming Listener or Event handler Example: Handling Button Events Example: Handling Mouse Events Example: Handling Keyboard Events.
Event-Driven Programming
Unit 12 Object-oriented programming: Event-driven programming for GUI Jin Sa.
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.
Intermediate Java1 An example that uses inner classes Week Four Continued.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
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.
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.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
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.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Event Driven Programming. Event-driven Programming In the early days of computing communication with the outside world was accomplished using a technique.
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.
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.
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.
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.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
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 CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
CS Lecture 04 Mice Lynda Thomas
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.
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.
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.
Event Handling and Listeners in SWING The practice of event handling.
Lesson 28: More on the GUI button, frame and actions.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
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.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
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
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
Programming in Java Event Handling
GUI Event Handling Nithya Raman.
GUI Programming III: Events
Event-driven programming for GUI
Web Design & Development Lecture 12
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Programming Graphical User Interface (GUI)
Presentation transcript:

For IST410 Students only Events-1 Event Handling

For IST410 Students only Events-2 Objectives l Concept of events l Event handling in Java l Action, Window and Mouse Events l Event Adapters

For IST410 Students only Events-3 l An event occurs when a user clicks a mouse button, presses or releases a key, or in general, interacts with the program l An event can be thought of as an external user action with the program; the sequence of this interaction is user dependent l User’s interaction is analogous to generating a signal to the program and the program would be expected to respond l It is then up to the program whether it responds or ignores the event Event: Introduction

For IST410 Students only Events-4 l A program, in order to respond to an event, must know three important pieces of information about the event m What type of event occurred? m Which component originated the event? m Who gets notified when the event occurs? l A GUI component may be able to generate more than one event type - for example, releasing a key generates a key released and a key typed event l Many components on a GUI screen may generate the same type of event - all buttons generate action events, program’s response may differ from one button to another l We may designate an object to listen for the arrival of an event i.e be notified Responding to an Event

For IST410 Students only Events-5 l An event model describes the mechanism of handling events in a programming environment l In the old days (jdk1.0), Java’s event handling was hierarchical - events were handled in the top layer of an application l In the current model, the event handling is delegation based - we delegate the responsibility of event handling for a component to an object and we tell all (or who so ever cares to listen) about it l Notice that in the delegation model, we can have any number of objects responsible for event handling Event Models

For IST410 Students only Events-6 l How do Java programs deal with the three pieces of information l What type of event occurred? m This is easy. Java programs do not worry about it, but JVM does. JVM recognizes the type of event and takes the responsibility of notifying the designated greeter l Which component originated the event? m This is a programming responsibility and we will see how to do that l Who gets notified when an event occurs? m In some sense, JVM is the starting point of the notification cycle. However, we designate Java objects as responsible parties to be notified by JVM What about the three pieces of information?

For IST410 Students only Events-7 l The notification process depends on registering an object with a component for an event l The objects responsible for event handling are sometimes called Listeners l Listeners are interface classes l Listeners declare abstract methods, each method is associated with a predefined type of event l When JVM recognizes an event, it notifies the registered listener which in turn executes the designated method l The program defines the response to an event by providing content to the interface methods Responding to an event

For IST410 Students only Events-8 Event Handling: Delegation Model Frame Panel Panel or Frame Event handlers Mouse Click i.e. an action event, can occur with either buttons void actionPerformed(ActionEvent e) { // }

For IST410 Students only Events-9 l Listener: an object responsible for ‘listening’ for events and responding l Registering Listener - add listener method of the GUI component is used to register the listener object l Event source: The GUI component l Steps: m An user initiated event occurs: for example a mouse click m JVM recognizes an event m The event object is sent to the registered listener object for that component m Listener object activates the handler method to respond Basics of the Event Model

For IST410 Students only Events-10 l Java defines a number of event listener Interfaces Listener TypeListens for ActionListenerAction Events ItemListenerChange in an item’s state WindowListenerWindow events MouseListenerMouse events MouseMotionListener Mouse motion events TextListenerChange in text value and others.... Listeners

For IST410 Students only Events-11 l Event sources may register one or more listeners m The current object is registered as a listener for a button named exit exit.addActionListener(this); m A separate class MyWindowListener is registered as the listener for a frame named jf jf.addWindowListener(new MyWindowListener()); l The registration process always takes the form component.addListenerName(listenerObject); l A component can register multiple listener jf.addWindowListener(new MyWindowListener()); jf.addMouseListener(this); Registering a Listener

For IST410 Students only Events-12 l A listener object is an instance of a class that implements the appropriate listener interface exit.addActionListener(this); m ‘this’ object is responsible for implementing the ActionListener interface l Since the current class is responsible for action events from the component exit, the class must be declared using the following format class implements ActionListener {.... } Listener Object

For IST410 Students only Events-13 l The listener interface may be implemented in a completely separated class jf.addWindowListener(new MyWindowListener()); m Listener is implemented in a separate class: MyWindowListener l The listener class should be implemented using the following format class implements WindowListener { } Listener Object

For IST410 Students only Events-14 l As you know, Listeners are interfaces l They declare abstract methods that an implementing class must implement, or be itself treated as abstract l For event handling, an implementing class must implement all abstract methods declared in the interface l Different interfaces define different abstract methods l For example, the only method defined in ActionListener public void actionPerformed (ActionEvent e) { //code to handle action events } Implementing a Listener

For IST410 Students only Events-15 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SimpleAction implements ActionListener { SwingFrameWithExit jf; Container cp; JButton one, two, three; JButton exit; JPanel jp; public SimpleAction() { ImageIcon bullet = new ImageIcon("bullet2.gif"); ImageIcon middle = new ImageIcon("middle.gif"); jf = new SwingFrameWithExit(); cp = jf.getContentPane(); cp.setLayout(new BorderLayout(2,2)); Example: Event handler in the same class as the event source SimpleAction declares the intention of handling action events in this class

For IST410 Students only Events-16 cp.setBackground(Color.red); // create the Panel jp = new JPanel(); jp.setBackground(Color.blue); // create the buttons and add them to the panel one = new JButton("ONE",bullet); jp.add(one); two = new JButton(middle); jp.add(two); three = new JButton("THREE",bullet); jp.add(three); cp.add(jp,BorderLayout.CENTER); // add panel to the frame exit = new JButton("EXIT"); exit.addActionListener(this); cp.add(exit,BorderLayout.SOUTH); Example: Event handler in the same class as the event source Registering event handler for the GUI component exit; ‘this’ object is the listener

For IST410 Students only Events-17 jf.setSize(300,300); jf.setVisible(true); } // Event handler for the Exit button public void actionPerformed(ActionEvent e) { System.exit(0); } public static void main(String[] args) { SimpleAction eac = new SimpleAction(); } Example: Event handler in the same class as the event source Implementation of the event handling method; JVM notifies this object (SimpleAction) about an action event, which in turn fires actionPerformed method and passes an ActionEvent object to this method Code to respond to the event, may be as needed

For IST410 Students only Events-18 l Code is exactly same as the previous example: SimpleAction.java, only changes are shown. The full source is in Example subdirectory for the module public class SimpleActionSeparateClass {..... public SimpleActionSeparateClass() { exit.addActionListener(new MyButtonHandler()); } public static void main(String[] args) { SimpleActionSeparateClass eac = new SimpleActionSeparateClass(); } class MyButtonHandler implements ActionListener { // Event handler for the Exit button public void actionPerformed(ActionEvent e) { System.exit(0); } Example: Event handler in a separate class No ‘implement’ here, since a separate class does event handling Registering by embedding the constructor of the listener object Separate class altogether, does contain the actionPerformed method though

For IST410 Students only Events-19 l Source of an event can be identified in more than one way l By finding a reference to the source object itself Object evtSource = e.getSource(); if (evtSource == exit) { // response code } l Necessary condition for this code to work exit is a valid reference in the actionPerformed method l Not always possible in a large application Identifying source of Events

For IST410 Students only Events-20 l An event source can be identified by comparing with the command string String s = e.getActionCommand(); if (“EXIT”  equals(s)) { // response code } l The button or other action generating objects must have a ‘face’ string equal to “EXIT” l Not very convenient in a large program or for internationalization Identifying source of Action Events

For IST410 Students only Events-21 l A command string can be attached to an event source exit.setActionCommand(“Close”); l The handler method can then compare with this String String s = e.getActionCommand(); if (“Close”  equals(s)) { // response code } l This technique is flexible, but program must ensure unique command string names. Identifying source of Action Events

For IST410 Students only Events-22 BorderLayoutEvents.java Example: Action event from multiple sources

For IST410 Students only Events-23 l Window Listeners are used to trap Window events l We can use window events to monitor events with frames and dialog boxes l The implementing class can be same as the class that originates the events, or a separate class l Since the WindowListener interface defines 7 abstract methods, the implementing class must implement all 7 of them l The next slide shows an example of a window listener class that can be registered to listen for window events m jf.addWindowListener(new MyWindowListener()); WindowListener Interface

For IST410 Students only Events-24 import java.awt.event.*; public class MyWindowListener implements WindowListener { public void windowClosed(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { System.exit(0); } l Shows all methods of the Window Listener interface WindowListener Interface Only closing event is implemented

For IST410 Students only Events-25 l MyWindowListener implements only one method m windowClosing(WindowEvent e) l Six other methods of the WindowListener interface must still be implemented even if all of these have empty actions l This approach is ‘bothersome’ l Java provides adapter classes matching each listener class where the listener has more than one abstract methods l For example, WindowListener has a corresponding WindowAdapter class Event handling through Adapters

For IST410 Students only Events-26 l Adapter classes are not abstract l These can be extended and only required method(s) can be overridden class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } l MyWindowAdapter class overrides the windowClosing method and provides for exiting from an application. Event handling through Adapters

For IST410 Students only Events-27 l All other methods of WindowAdapter class are then inherited by the MyWindowAdapter; these inherited methods have empty implementation l Such an adapter object can be registered as the event handler for a frame using similar syntax as in the case of the listener class object m jf.addWindowListener(new MyWindowAdapter()); l Java provides adapter classes for all listeners with more than one abstract method Event handling through Adapters

For IST410 Students only Events-28 l Receives mouse events excluding motion l Name of the interface is MouseListener When called void mouseClicked(MouseEvent e) mouse is clicked void mouseEntered(MouseEvent e) enters a component void mouseExited(MouseEvent e) exits a component void mousePressed(MouseEvent e) mouse is pressed void mouseReleased(MouseEvent e) mouse is released l Yes, there is a MouseAdapter class Mouse Listener

For IST410 Students only Events-29 l int getClickCount() - gets you the number of mouse clicks l Point getPoint() - Returns the x,y coordinates of the mouse event, These coordinates are screen coordinates in pixels l int getX() - Returns the x coordinate of the event l int getY() - Returns the y coordinate of the event Interesting methods of Mouse Event

For IST410 Students only Events-30 l Interface to track Mouse Motion l There is an equivalent MouseMotionAdapter class l Since mouse motion events get constantly fired as a mouse moves, efficiency dictates a separation between motion and mouse down. l Two event types void mouseDragged(MouseEvent e) - fires when a mouse button is pressed on a component and then dragged void mouseMoved(MouseEvent e) - fires when the mouse button is moved on a component without any button down Mouse Motion Listener

For IST410 Students only Events-31 MouseEventDemo.java Example: Mouse Events