3461 Sequential vs. Event-driven Programming Reacting to the user.

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

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-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
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.
OOP Java1 Event Handling Overview Listeners, Adapters and Event Sources Inner classes Event Handling Details Applets and GUI Applications 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.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
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.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
Chapter 12 Applets and Advanced Graphics  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets.
Welcome to CIS 083 ! Events CIS 068.
Chapter 12 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 14 Event-Driven Programming.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
– 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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
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.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
Event Handling. Event Driven Programming Flow of programs is determined by events. The Operating system recognizes events and passes them to the particular.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
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
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
COSC 3461: Module 2 Control Flow Paradigms: Reacting to the User.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
Lesson 6 Programming Techniques Event Handling /EvH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Creating User Interfaces Event-Driven Programming.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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.
Event Handling and Listeners in SWING The practice of event handling.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
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.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
1 DemoBasic_v3, DemoBasic_v4 JButton JLabel. 2 Registering an ActionListener Register by invoking the following from within constructor DemoBasicFrame.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
CSC 205 Programming II Lecture 5 AWT - I.
Chapter 14 Event-Driven Programming
Programming in Java, 2e Sachin Malhotra Saurabh Choudhary.
CHAPTER Reacting to the user.
Chapter 12 Event-Driven Programming
A First Look at GUI Applications
Ellen Walker Hiram College
GUI Event Handling Nithya Raman.
Introduction to Computing Using Java
Chapter 16 Event-Driven Programming
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
ACM programming contest
Presentation transcript:

3461 Sequential vs. Event-driven Programming Reacting to the user

3461P Outline  Sequential programming  Event-driven programming  Modes

3461P Sequential Programming  In sequential programs, the program is under control  The user is required to synchronize with the program:  Program tells user it’s ready for more input  User enters more input and it is processed  Examples:  Command-line prompts (DOS, UNIX)  LISP interpreters  Shouldn’t the program be required to synchronize with the user?

3461P Sequential Programming (2)  Flow of a typical sequential program  Prompt the user  Read input from the keyboard  Parse the input (determine user action)  Evaluate the result  Generate output  Repeat

3461P Example TranslateEnglish.java Prompt the user User input Output results

3461P Sequential Programming (3)  Advantages  Architecture is iterative (one step at a time)  Easy to model (flowcharts, state machines)  Easy to build  Limitations  Can’t implement complex interactions  Only a small number of features possible  Interaction must proceed according to a pre-defined sequence  To the rescue… Event-driven programming

3461P Outline  Sequential programming  Event-driven programming  Modes

3461P Event-driven Programming  Instead of a user reacting to a program, the program reacts to the user  All communication from user to computer occurs via events and the code that handles the events  An event is an action that happens in the system  A mouse button pressed or released  A keyboard key is hit  A window is moved, resized, closed, etc.

3461P Types of Events  Typically two different classes of events  User-initiated events  Events that result directly from a user action  e.g., mouse click, move mouse, key press  System-initiated events  Events created by the system, as it responds to a user action  e.g., highlight a button, scrolling text, re-drawing a window  Both types of events need to be processed in a UI  User-created events may initiate system-generated events

3461P Example TranslateEnglishGUI.java

3461P What is Pig Latin? Pig Latin is a fake dialect. For words which begin with a single consonant take the consonant off the front of the word and add it to the end of the word. Then add ay after the consonant. Here are some examples: cat = atcay dog = ogday simply = implysay noise = oisnay

3461P What just Happened?  Event-driven programming takes us far beyond sequential programming  Let’s examine the organization of the example program  First, a few words on Java Events

3461P Java’s Event Class Hierarchy EventObject AWTEvent ActionEvent ComponentEvent InputEventWindowEvent MouseEvent KeyEvent Used in example program Note: this diagram is not complete. It just shows the most common event classes

3461P Java Events  When a user types characters or uses the mouse, Java’s window manager sends a notification to the program that an event has occurred  E.g., when the user presses a key on the keyboard, a key pressed event occurs  There are many, many kinds of events (e.g., key pressed, key released, key typed)  Many are of no interest  Some are of great interest

3461P Java Events (2)  To receive notification of events of interest, a program must install event listener objects  If is not enough to simply know that an event has occurred; we need to know the event source  E.g., a key was pressed, but in which of several text fields in the GUI was the key pressed?  So, an event listener must be installed for particular components that may generate the event  Let’s look at the code. First, the big picture…

3461P import... public class NameOfProgram { public static voic main(String[] args) { } public class NameOfProgramFrame { } Identify packages containing classes used in the program 1. Construct the GUI frame 2. Give it a title 3. Show it 4. Done!!!! Suggested naming convention (just add “Frame” to name of program) All the work is done here

3461P import... public class NameOfProgram { public static voic main(String[] args) { } public class NameOfProgramFrame extends JFrame { } Our GUI frame class is actually a JFrame – extended and modified to suit our needs

3461P JFrame  Class in the javax.swing package  Sun’s Swing toolkit is Java’s most advanced toolkit  Life before Swing…  AWT (abstract windowing toolkit)  AWT used “native” UI components (unique to local system)  This creates inconsistencies across platforms  UI components of AWT are now obsolete  AWT still used for drawing, images,etc.  Swing paints the components itself  Advantage: code is consistent across platforms  Disadvantage: results in “big” programs (lots of memory!)  Swing still uses many features of AWT

3461P import... public class NameOfProgram { public static voic main(String[] args) { } public class NameOfProgramFrame extends Jframe implements KeyListener { } Our GUI class implements the methods of the KeyListener listener

3461P... public class NameOfProgramFrame extends Jframe implements KeyListener { public... private... public class NameOfProgramFrame() {} public void keyPressed(KeyEvent ke) {} public void keyReleased(KeyEvent ke) {} public void keyTyped(KeyEvent ke) {} public... private... } Declare variables (aka “fields”, “attributes”) Constuctor Must implement all three KeyListener methods, even though just one is used. Other methods

3461P Frame Constuctor  Must…  Create and configure the GUI components  Install (“add”) listeners  Listeners are not just installed, they must be associated with particular GUI components  Arrange components in panel(s)  Get the JFrame’s content pane  Add panel(s) to content pane

3461P Listeners  Java’s listener classes are actually interfaces (not classes)  What is an interface?

3461P Interfaces  The definition of a class includes both the design of the class and its implementation  Sometimes it is desireable only to design a class, leaving the implementation for later  This is accomplished through an interface  An interface contains only the design of a class  Includes signatures for its members (methods and fields)  No implementation is provided

3461P Characteristics of Interfaces  Interfaces…  Do not have instance variables  You cannot instantiate an object of an interface  Include only abstract methods  Methods have a signature (i.e., a name, parameters, and return type)  Methods do not have an implementation (i.e., no code)  Include only public methods and fields  Does not make sense to define private members if the public members that could potentially use them are themselves not implemented

3461P Listeners (revisited)  The signature of our extended JFrame class includes the clause implements KeyListener  This means our class must include definitions for the methods of the KeyListener listener  Thus…  Our implementation includes the code we want executed when a key is pressed, released, and/or typed  Q: What is the difference between “pressed” and “typed”? A: Look in the API Spec! public void keyPressed(KeyEvent ke) {} public void keyReleased(KeyEvent ke) {} public void keyTyped(KeyEvent ke) {}

3461P Installing Listeners  It is not enough simply to implement the methods of a listener  The listener must also be “installed” (aka “registered”, “added”)  Furthermore, it must be installed for the component to which the listener methods are to be associated  Thus (from our example program) enterArea.addKeyListener(this); Component to which the listener methods are to be associated An object of a class that implements the listener methods

3461P Installing Listeners (2)  Consider the method addKeyListener  Fact #1: addKeyListener is a method of the Component class (check the API Spec)  Fact #2: enterArea (from our example) is an object (instance variable) of the JTextArea class  Fact #3: Through inheritance, a JTextArea object is a Component object  Conclusion: the addKeyListener method can be invoked on enterArea

3461P Installing Listeners (3)  Signature for the addKeyListener method:  Description:  In our example, we used this as the “specified key listener”  Indeed, the current instance of our extended JFrame class (“this”) is a key listener because it implements the key listener methods  Result: when a key pressed event occurs on the enterArea component, the keyPressed method in our extended JFrame class will execute! public void addKeyListener(KeyListener) Adds the specified key listener to receive key events from this component.

3461P Let’s Say That Again… When a key pressed event occurs on the enterArea component, the keyPressed method in our extended JFrame class will execute!

3461P Processing Events  Signature for the keyPressed method:  When our keyPressed method executes, it receives a KeyEvent object as an argument  We use the KeyEvent object to  Determine which key was pressed, using  getKeyChar, getKeyCode, etc.  Determine the source of the event, using  getSource  “Determine the source of the event” is important if there is more than one component registered to receive key events (not the case in our example program) public void keyPressed(KeyEvent ke)

3461P Event Sources  Java’s event classes are all subclasses of EventObject (see earlier slide)  EventObject includes the getSource method:  Didn’t need this in our example program, because only one object (enterArea) was registered to generate key events  So, when the keyPressed method executes we know it is because a key was pressed in enterArea  But, let’s say we have two JTextArea components: enterArea1 and enterArea2 (next slide) public Object getSource()

3461P Event Sources (2) public void keyPressed(KeyEvent ke) { if (ke.getSource() == enterArea1) { // code for enterArea1 key pressed events } else if (ke.getSource() == enterArea2) { // code for enterArea2 key pressed events }

3461P Back to the Example Program…... public class NameOfProgramFrame extends Jframe implements KeyListener {... private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); }

3461P Adapters  Provided as a convenience  Include dummy implementations of listener methods public abstract class WindowAdapter implements WindowListener { void windowActivated(WindowEvent we) {} void windowClosed(WindowEvent we) {} void windowClosing(WindowEvent we) {} void windowDeactivated(WindowEvent we) {} void windowDeiconified(WindowEvent we) {} void windowIconified(WindowEvent we) {} void windowOpened(WindowEvent we) {} }

3461P Using an Adapter Class  Define an inner class that extends the adapter class  Implement the listener methods of interest  Ignore other listener methods  In the frame constructor, use the appropriate “add” method to add an object of the extended adapter class  In our example program… this.addWindowLisener(new WindowCloser());

3461P Examples of Liseners and Adapters Listeners (# methods)Adapters KeyListener (3)KeyAdapter WindowListener (7)WindowAdapter MouseListener (5)MouseAdapter MouseMotionListener (2)MouseMotionAdapter ActionListener (1)- ItemListener (1)-

3461P Extending Adapters vs. Implementing Listeners  Largely a matter personal choice  Our example program does both  The KeyListener methods were implemented  The WindowAdapter class was extended  Could have done the opposite, i.e.,  Extend the KeyAdapter class  Implement the WindowListener methods  Note: a Java class can implement many listener classes, but it can extend only one class  Java does not include multiple inheritance (unlike C++)

3461P Pros and Cons  Using adapter classes  Advantage  Only the listener methods needed are defined  Disadvantage  A bit complicated to setup  Need to defined an inner class, then instantiate an object of the inner class to pass to the appropriate “add” method  Implementing listener methods  Advantage  A class can implement many different listeners  Disadvantage  Must implement all the methods defined in the listener (even those not used)

3461P The Good, The Bad, and The Arcane  Do you like creating code that mere mortals find incomprehensible? If so, you’ll like this one.  Delete the inner class definition…  and replace this…  with this… this.addWindowLisener(new WindowCloser()); private class WindowCloser extends WindowAdapter {public void windowClosing(WindowEvent we) {System.exit(0); } this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);} });

3461P Example Program MouseEventsDemo.java

3461P Outline  Sequential programming  Event-driven programming  Modes

3461P Coping With Complexity  How do we cope with complexity?  Typically, the interface is designed with modes  Each mode represents a different state of the system  User input must be appropriate for the current state  Moded systems require lots of variables to represent the state of the system

3461P Examples of Modes  Draw programs  Use a mode to determine what is being drawn  E.g., line mode, rectangle mode, circle mode  Universal remote controls  E.g., TV mode, VCR mode  vi editor on unix  Insert mode, command mode  Sport watches (Yikes! Too many modes!)

3461P Example MS PowerPoint Normal Outline Slide Slide sorter Slide show Five “Wiew modes”

3461P Modes in GUIs  One simple way is to use radio buttons

3461P Example TranslateEnglishGUI2.java

3461P Problems With Modes  Confusing if too many modes (the user has to remember the salient ones)  More modes makes it easier for users to make errors (right command, wrong mode)  Need feedback as to current mode (vi doesn’t!).  Need a mechanism to switch modes  Modes do not scale well  Need a more advanced model to simplify windows programming

3461P Next Topic…