CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.

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

1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
Graphic User Interfaces Layout Managers Event Handling.
TCU CoSc Programming with Java Handling Events.
Event Handling Events and Listeners Timers and Animation.
Event-Driven Programming
Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
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.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
GUI Programming in Java: Event Handling & More Components Corresponds with Chapter 14, Chapter 15.
Welcome to CIS 083 ! Events CIS 068.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
Dale Roberts GUI Programming using Java - Event Handling Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
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.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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.
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.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
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,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
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.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Event Handling CS 21a: Introduction to Computing I First Semester,
View  view  presents the user with a sensory (visual, audio, haptic) representation of the model state  a user interface element (the user interface.
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.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
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.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUI Programming using Java - Event Handling
GUIs and Events Rick Mercer.
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
CompSci 230 S Programming Techniques
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Advanced User Interfaces
Programming in Java Event Handling
Ellen Walker Hiram College
Event Handling CS 21a: Introduction to Computing I
GUI Event Handling Nithya Raman.
Event-driven programming for GUI
Introduction to Event Handling
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming

CS-1020 Dr. Mark L. Hornick 2 Writing GUI applications requires a style of program control called event-driven programming An event occurs when a user (like you) interacts with a GUI object (like a JButton)

CS-1020 Dr. Mark L. Hornick 3 Spy++ Demo Spy++ is a utility for snooping on events that are generated within Windows

CS-1020 Dr. Mark L. Hornick 4 Event-driven programs… …contain two special types of objects: Event source objects - GUI objects (like JButton) which generate the events When an event is generated, the operating/windowing system captures the generated event Event listener objects Subscribe to the operating/windowing system to be notified when certain events occur

CS-1020 Dr. Mark L. Hornick 5 Event Handling When the operating system captures an event, it notifies a subscribed event listener object by calling the event listener’s event handling method If no event listener object is subscribed to listen for an event, the events from the event source object are ignored OS

CS-1020 Dr. Mark L. Hornick 6 There are many types of Events One of the most common is an Action Event Some Events and Their Associated Event Listeners Act that Results in the EventEvent Listener Type Action: User clicks a button, presses Enter while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window) WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener Any property in a component changes such as the text on a label PropertyChangeListener

CS-1020 Dr. Mark L. Hornick 7 Handling Action Events An object that can be registered as an Action Listener (i.e. can subscribe to Action Events) must be an instance of a class that is declared specifically for the purpose That is, it the class must implement the ActionListener interface To subscribe an Action Listener to an Action Event source, the event source’s addActionListener method must be called with a reference to the Action Listener object as its argument. i.e. JButton has an addActionListener() method: JButton btnQuit = new JButton(“Quit”); btnQuit.addActionListener( eventHandler ); // eventHandler is an ActionListener

CS-1020 Dr. Mark L. Hornick 8 ActionListener is a Java interface Recall: Any class that implements a Java interface must provide the method body to all the methods defined in the interface The ActionListener interface only defines a single method – actionPerformed()

CS-1020 Dr. Mark L. Hornick 9 Which class or classes should be Action Listeners? First alternative: 1. Have a separate class listen for events This separates GUI creation and event handling Could be good if there is a lot of non-GUI logic involved in responding to events

CS-1020 Dr. Mark L. Hornick 10 Defining a separate class that implements ActionListener: import java.awt.event.*; class EventHandler implements ActionListener {... public void actionPerformed( ActionEvent evt ){... } The system notifies an Action Listener by calling the listener’s actionPerformed() method The actionPerformed() method is passed a single argument: a reference to an ActionEvent object

CS-1020 Dr. Mark L. Hornick 11 We need to handle events from multiple sources… A single Action Listener can be subscribed to multiple event sources (e.g. many buttons) The Action Listener must be able to distinguish one source from another

CS-1020 Dr. Mark L. Hornick 12 Determining an event source – method 1: by event object First, we use the Java instanceof operator to determine the class to which the event source belongs: public void actionPerformed( ActionEvent evt ){ if (evt.getSource() instanceof JButton ){ //event source is a button (but which one??)... } else if (evt.getSource() instanceof JTextFrame ) { //event source is a JTextFrame (but which one??)... }

CS-1020 Dr. Mark L. Hornick 13 Once we know the Class of the item that generated the event… …we use the getSource() method to return a reference to the Object that generated the event: if( evt.getSource() instanceof JButton ){ JButton btn= (JButton) evt.getSource(); Note that the getSource returns a reference to an object of the class Object An Object reference can refer to any type of class, so we typecast the returned Object reference to a JButton reference in order to be able to access JButton methods.

CS-1020 Dr. Mark L. Hornick 14 Identifying the specific event object Once you know that the source was a JButton, you can check the source against your program’s inventory of JButton objects: if (evt.getSource() instanceof JButton ){ //event source is a button (but which one??) JButton btn = (JButton)evt.getSource(); if( btn == btnQuit ) … else if( btn == btnCancel ) … }

CS-1020 Dr. Mark L. Hornick 15 Determining an event source – method 2: by action command The event’s getActionCommand() method can be used to get the text of the object’s Action Command that generated the event: String command = evt.getActionCommand(); if(command.equals(“Quit”) // the Quit button... else if( command.equals(“Cancel”) // Cancel button By default, the Action Command text is the same as the text that appears on the button face (for a JButton) or the text with a JTextField So what do you do if the button does not contain text? And a user can enter just about any text into a JTextField

CS-1020 Dr. Mark L. Hornick 16 setActionCommand method The setActionCommand() method can be used to set the Action Command text for any component btnQuit = new JButton ("Quit"); btnQuit.setActionCommand(“Close”); textDate = new JTextField(); textDate.setActionCommand(“Begin”); The text of the Action Command is up to you Calling setActionCommand() does not change the text on the button face or within the text field (that’s done with setText() )

CS-1020 Dr. Mark L. Hornick 17 Multiple Action Event handlers Likewise, multiple Action Listeners can be subscribed to a single event source. When an event source generates an event, the system notifies all matching registered ActionListeners Using multiple listeners is not very common

CS-1020 Dr. Mark L. Hornick 18 Some consequences of implementing a separate class for Action Listeners 1. GUI creation and event handling are separated Could be good if there is a lot of non-GUI logic involved in responding to events 2. We could separate event handling into several classes in order to avoid all the if and instanceOf logic for determining the event source 3. The Action Listener classes can’t access the variables that reference GUI objects unless the objects are public (not a good approach) or public accessor methods are provided to access each UI component (good, but that could lead to a lot of accessors)

CS-1020 Dr. Mark L. Hornick 19 Which class or classes should be Action Listeners? Second alternative: Have the class that created the GUI in the first place listen for all events GUI creation and event handling all in a single class But still lots of if statements and instanceOf checks inside the actionPerformed method

CS-1020 Dr. Mark L. Hornick 20 UML Sequence Diagram

CS-1020 Dr. Mark L. Hornick 21 Which class or classes should be Action Listeners? Third alternative: Use separate inner classes to listen for events GUI creation and event handling separated Could be good if there is a lot of non-GUI logic involved in responding to events Could separate event handling into several classes in order to avoid all the if and instanceOf logic for determining the event source The Action Listener inner classes CAN access the variables that reference GUI objects (keeping the objects private)

CS-1020 Dr. Mark L. Hornick 22 What’s an inner class? An inner class is another class defined inside the same java file - inside the enclosing class import java.awt.event.*; class MyGUIClass { // create GUI and implement usual methods here // define an inner class for handling events class AnActionListener implements ActionListener { public void actionPerformed( ActionEvent evt ){ // handle events here } } // end of inner class } // end of enclosing class

CS-1020 Dr. Mark L. Hornick 23 Inner class properties The inner class can access all the members (public or private) of the enclosing class The inner class is private to the outside world You can’t create an instance of an inner class – only the enclosing class You can have any number of inner classes

CS-1020 Dr. Mark L. Hornick 24 Handling events Multiple Action Listeners can handle multiple related events This varies according to the judgment of the program designers

CS-1020 Dr. Mark L. Hornick 25 Performance Issues Event-handling code executes in an single thread, the event-dispatching thread. This ensures that each event handler finishes execution before the next one executes. Painting code also executes in the event- dispatching thread. Therefore, event-handling code should execute quickly so that the program’s GUI stays responsive. If an event takes too long to execute, the GUI will freeze--that is, it won’t repaint or respond to mouse clicks.