CSE 331 Software Design & Implementation

Similar documents
Lecture 19 GUI Events

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

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

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

CS 251 Intermediate Programming GUIs: Event Listeners

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Class 16: The Swing Event Model

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

Graphical User Interfaces 2

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

The AWT Event Model 9

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

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

G51PRG: Introduction to Programming Second semester Applets and graphics

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

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

GUI Software Architecture

Jonathan Aldrich Charlie Garrod

Graphical User Interface (GUI)

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

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

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame 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!

Event-driven Programming: GUIs

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

Java Programming. Events and Listeners

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

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA. Assignment No. 4

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

Event Handling in JavaFX

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

Graphical User Interfaces 2

Lecture 18 Java Graphics and GUIs

GUI Event Handlers (Part I)

Graphical User Interfaces 2

CS11 Java. Fall Lecture 3

Graphical User Interfaces (GUIs)

CSE 331 Software Design & Implementation

COMPSCI 230. Software Design and Construction. Swing

Java: Graphical User Interfaces (GUI)

Programming Languages and Techniques (CIS120)

MVC: Model View Controller

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

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

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Programming Languages and Techniques (CIS120)

BASICS OF GRAPHICAL APPS

Graphical User Interface (GUI)

Swing from A to Z Some Simple Components. Preface

Advanced Java Programming (17625) Event Handling. 20 Marks

Programming Languages and Techniques (CIS120)

Introduction to concurrency and GUIs

MIT AITI Swing Event Model Lecture 17

Java GUI Design: the Basics

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

UI Software Organization

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

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

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

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

CSE 331 Software Design & Implementation

Windows and Events. created originally by Brian Bailey

Dr. Hikmat A. M. AbdelJaber

Introduction to the JAVA UI classes Advanced HCI IAT351

Lab 10: Inheritance (I)

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.

Programming Languages 2nd edition Tucker and Noonan"

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

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)

Unit 7: Event driven programming

Chapter 15 Event-Driven Programming and Animations

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

Chapter 1 GUI Applications

Programming Languages and Techniques (CIS120)

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

The init() Method. Browser Calling Applet Methods

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

Java Swing Introduction

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

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

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

GUI Components: Part 1

CS211 GUI Dynamics. Announcements. Motivation/Overview. Example Revisted

SINGLE EVENT HANDLING

(Incomplete) History of GUIs

2. (True/False) All methods in an interface must be declared public.

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

COMP 401 Recitation 8. Observer Pattern

CS 2113 Software Engineering

MOBILE COMPUTING 1/20/18. How many of you. CSE 40814/60814 Spring have implemented a command-line user interface?

Graphical interfaces & event-driven programming

Transcription:

CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1

The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes (and a quick look at Java 8 lambdas) Proper interaction between UI and program threads 2

Event-driven programming Many applications are event-driven GUI programs: Program initializes itself on startup 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, optimization, 3

Kinds of GUI events Typical events handled by a GUI program: Keyboard: key press or release, sometimes with modifiers like shift/control/alt/etc. Mouse move/drag/click, button press, button release also can have 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) 4

Events in Java AWT/Swing 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 generate 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 5

Event objects 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 6

Event listeners 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, An event object is passed as a parameter to the event listener method 7

Example: button 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 8

Which button is which? 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. Similar mechanisms to decode other events 9

Listener classes 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-blown class when all we want is to house a method to be called after a button click? A more convenient(?) Java shortcut: anonymous inner classes 10

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 11

Example Method call parameter list new expression to create class instance Class or interface being extended/implemented (can include constructor parameters) button.addactionlistener(new ActionListener(){ ); } public void actionperformed(actionevent e) { } model.dosomething() Implementation of method for this anonymous class Brackets surrounding new class definition 12

Example ButtonDemo2.java 13

Lambdas (Java 8) [optional] Why create a complete class (anonymous or otherwise) if you just want to define a method to be called when a button is clicked? Java 8 provides lambdas anonymous methods for situations like this Limitation: a lambda is not a complete object, so if you want private state, constructors, etc., you want an anonymous or named class instead Many other uses, especially with container classes Feel free to use in your code if you understand what s happening ButtonDemo3.java 14

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 callbacks like actionlistener or paintcomponent, etc. defined in your code 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 whenever the window manager calls it so any data it needs to render must be prepared in advance 15

Event handling and repainting program window manager (UI) 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. 16

Working in the UI thread Event handlers should not do a lot of work 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) 17

Synchronization issues? Yes, there can be synchronization problems (cf. CSE332, CSE451, CSE452, ) Not generally an issue in well-behaved programs, but can happen Advice: Keep event handling short Call repaint when data is ready, not when only 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 by scheduling computations to be run by the UI thread (Swing tutorial, Core Java, ) 18

Larger example bouncing balls 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 (maybe not even particularly good) Unlikely to be directly appropriate for your project Use it for ideas and inspiration, and feel free to steal small parts if they really fit Enjoy! 19