Lecture 19 GUI Events

Similar documents
CSE 331 Software Design & Implementation

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CSE 331 Software Design & Implementation

Event Driven Programming

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

CS 251 Intermediate Programming GUIs: Event Listeners

Class 16: The Swing Event Model

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphical User Interfaces 2

CS11 Java. Fall Lecture 4

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

G51PRG: Introduction to Programming Second semester Applets and graphics

The AWT Event Model 9

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Lecture 18 Java Graphics and GUIs

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Composite Pattern Diagram. Explanation. JavaFX Subclass Hierarchy, cont. JavaFX: Node. JavaFX Layout Classes. Top-Level Containers 10/12/2018

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

GUI Software Architecture

CSSE 220. Event Based Programming. Check out EventBasedProgramming from SVN

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Java Programming. Events and Listeners

Introduction to GUIs. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2014

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Jonathan Aldrich Charlie Garrod

Graphical User Interfaces 2

Graphical User Interface (GUI)

Event-driven Programming: GUIs

CS11 Java. Fall Lecture 3

Anonymous Classes. A short-cut for defining classes when you want to create only one object of the class.

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Event-Driven Programming with GUIs. Slides derived (or copied) from slides created by Rick Mercer for CSc 335

CS 112 Programming 2. Lecture 14. Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations

BASICS OF GRAPHICAL APPS

COMPSCI 230. Software Design and Construction. Swing

Programming Languages and Techniques (CIS120)

CSE 331 Software Design & Implementation

Event Handling in JavaFX

GUI Event Handlers (Part I)

Graphical User Interfaces 2

SD Module-1 Advanced JAVA

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

SD Module-1 Advanced JAVA. Assignment No. 4

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Programming Languages and Techniques (CIS120)

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

MVC: Model View Controller

Advanced Java Programming (17625) Event Handling. 20 Marks

Java: Graphical User Interfaces (GUI)

MIT AITI Swing Event Model Lecture 17

Programming Languages and Techniques (CIS120)

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Page 1. Human-computer interaction. Lecture 2: Design & Implementation. Building user interfaces. Users and limitations

UI Software Organization

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Graphical User Interfaces (GUIs)

Introduction to concurrency and GUIs

Introduction to the JAVA UI classes Advanced HCI IAT351

CSE1720. Objectives for this class meeting 2/10/2014. Cover 2D Graphics topic: displaying images. Timer class, a basic ActionListener

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Which of the following syntax used to attach an input stream to console?

Graphical User Interface (GUI)

Chapter 1 GUI Applications

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Java GUI Design: the Basics

The init() Method. Browser Calling Applet Methods

Swing from A to Z Some Simple Components. Preface

Events. Dispatch, event-to-code binding. Review: Events Defined 1/17/2014. occurrence.

Dr. Hikmat A. M. AbdelJaber

Windows and Events. created originally by Brian Bailey

GUI Components: Part 1

Programming Languages 2nd edition Tucker and Noonan"

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Lab 10: Inheritance (I)

COMP 401 Recitation 8. Observer Pattern

Unit 7: Event driven programming

AP Computer Science Unit 13. Still More Graphics and Animation.

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Event Dispatch. Interactor Tree Lightweight vs. Heavyweight Positional Dispatch Focus Dispatch. Event Architecture. A pipeline: Event Capture

GUI in Java TalentHome Solutions

Chapter 15 Event-Driven Programming and Animations

CS 170 Java Programming 1. Week 15: Interfaces and Exceptions

Sharing is the Key. Lecture 25: Parallelism. Canonical Example. Bad Interleavings. Common to have: CS 62 Fall 2016 Kim Bruce & Peter Mawhorter

Programming Languages and Techniques (CIS120)

CSE 331 Software Design & Implementation

Java Programming Lecture 7

PIC 20A Anonymous classes, Lambda Expressions, and Functional Programming

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Lab. Lecture 26: Concurrency & Responsiveness. Assignment. Maze Program

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

CS 2113 Software Engineering

Transcription:

CSE 331 Software Design and Implementation Lecture 19 GUI Events The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction between UI and program threads Zach Tatlock / Winter 2017 Event-driven programming Kinds of GUI events Many applications are event-driven programs (most GUIs!): Program initializes itself, then enters an event loop Abstractly: do { e = getnextevent(); process event e; } while (e!= quit); Contrast with application- or algorithm-driven control where program expects input data in a particular order Typical of large non-gui applications like web crawling, payroll, simulation, Typical events handled by a GUI program: Mouse move/drag/click, button press, button release Keyboard: key press or release, sometimes with modifiers like shift/control/alt/etc. Finger tap or drag on a touchscreen Joystick, drawing tablet, other device inputs Window resize/minimize/restore/close Network activity or file I/O (start, done, error) Timer interrupt (including animations)

Events in Java AWT/Swing Event objects Many (most?) of the GUI widgets can generate events (button clicks, menu picks, key press, etc.) Handled using the Observer Pattern: Objects wishing to handle events register as observers with the objects that generates them When an event happens, appropriate method in each observer is called As expected, multiple observers can watch for and be notified of an event generated by an object A Java GUI event is represented by an event object Superclass is AWTEvent Some subclasses: ActionEvent GUI-button press KeyEvent keyboard MouseEvent mouse move/drag/click/button Event objects contain information about the event UI object that triggered the event Other information depending on event. Examples: ActionEvent text string from a button MouseEvent mouse coordinates Event listeners Example: button Event listeners must implement the proper interface: KeyListener, ActionListener, MouseListener (buttons), MouseMotionListener (move/drag), Or extend the appropriate library abstract class that provides empty implementations of the interface methods When an event occurs, the appropriate method specified in the interface is called: actionperformed, keypressed, mouseclicked, mousedragged, Create a JButton and add it to a window Create an object that implements ActionListener (containing an actionperformed method) Add the listener object to the button s listeners ButtonDemo1.java An event object is passed as a parameter to the event listener method

Which button is which? Listener classes Q: A single button listener object often handles several buttons. How to tell which button generated the event? A: an ActionEvent has a getactioncommand method that returns (for a button) the action command string Default is the button name (text), but usually better to set it to some string that will remain the same inside the program code even if the UI is changed or button name is translated. See button example. ButtonDemo1.java defines a class that is used only once to create a listener for a single button Could have been a top-level class, but in this example it was an inner class since it wasn t needed elsewhere But why a full-scale class when all we want is to create a method to be called after a button click? Alas, no lambdas (function closures) before Java 8 A more convenient shortcut: anonymous inner classes Similar mechanisms to decode other events Anonymous inner classes Idea: define a new class directly in the new expression that creates an object of the (new) anonymous inner class Specify the superclass to be extended or interface to be implemented Override or implement methods needed in the anonymous class instance Can have methods, fields, etc., but not constructors But if it starts to get complex, use an ordinary class for clarity (nested inner class if appropriate) Warning: ghastly syntax ahead Example Method call parameter list button.addactionlistener(new ActionListener(){ public void actionperformed(actionevent e) { ); } } new expression to create class instance model.dosomething() Implementation of method for this anonymous class Class or interface being extended/implemented (can include constructor parameters) Brackets surrounding new class definition

Example Program thread and UI thread Recall that the program and user interface are running in separate, concurrent threads All UI actions happen in the UI thread including the callbacks like actionlistener or paintcomponent, etc. defined in your code ButtonDemo2.java After event handling and related work, call repaint() if paintcomponent() needs to run. Don t try to draw anything from inside the event handler itself (as in you must not do this!!!) Remember that paintcomponent must be able to do its job by reading data that is available whenever the window manager calls it Event handling and repainting Working in the UI thread program window manager (UI) Event handlers should not do a lot of work actionperformed(e) repaint() paintcomponent(g) Remember: your program and the window manager are running concurrently: Program thread User Interface thread It s ok to call repaint from an event handler, but never call paintcomponent yourself from either thread. If the event handler does a lot of computing, the user interface will appear to freeze up (Why?) If there s lots to do, the event handler should set a bit that the program thread will notice. Do the heavy work back in the program thread. (Don t worry finding a path for campus maps should be fast enough to do in the UI thread)

Synchronization issues? Larger example bouncing balls Yes, there can be synchronization problems (cf. CSE332, CSE451, ) Not usually an issue in well-behaved programs, but can happen Some advice: Keep event handling short Call repaint when data is ready, not when partially updated Don t update data in the UI and program threads at the same time (particularly for complex data) Never call paintcomponent directly (Have we mentioned you should never ever call paintcomponent? And don t create a new Graphics object either.) If you are building industrial-strength UIs, learn more about threads and Swing and how to avoid potential problems A hand-crafted MVC application. Origin is somewhere back in the CSE142/3 mists. Illustrates how some swing GUI components can be put to use. Disclaimers: Not the very best design Unlikely to be directly appropriate for your project Use it for ideas and inspiration, and feel free to steal small bits if they really fit Enjoy!