CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Similar documents
Lecture 19 GUI Events

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation

Event Driven Programming

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

CS11 Java. Fall Lecture 4

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

Class 16: The Swing Event Model

CS 251 Intermediate Programming GUIs: Event Listeners

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

Programming Languages and Techniques (CIS120)

Graphical User Interfaces 2

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

GUI Software Architecture

G51PRG: Introduction to Programming Second semester Applets and graphics

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

Announcements. Introduction. Lecture 18 Java Graphics and GUIs. Announcements. CSE 331 Software Design and Implementation

Jonathan Aldrich Charlie Garrod

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

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

The AWT Event Model 9

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

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!

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

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

Graphical User Interfaces 2

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

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

Event-driven Programming: GUIs

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

Programming Languages and Techniques (CIS120)

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

CS11 Java. Fall Lecture 3

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

Java Programming. Events and Listeners

COMPSCI 230. Software Design and Construction. Swing

Programming Languages and Techniques (CIS120)

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

Graphical User Interface (GUI)

BASICS OF GRAPHICAL APPS

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

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

MIT AITI Swing Event Model Lecture 17

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Programming Languages and Techniques (CIS120)

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

MVC: Model View Controller

GUI Event Handlers (Part I)

Programming Languages and Techniques (CIS120)

Programming Languages and Techniques (CIS120)

Introduction to concurrency and GUIs

Graphical User Interfaces 2

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

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Event Handling in JavaFX

SD Module-1 Advanced JAVA

CSE 331 Software Design & Implementation

SD Module-1 Advanced JAVA. Assignment No. 4

Java: Graphical User Interfaces (GUI)

Chapter 1 GUI Applications

Lecture 18 Java Graphics and GUIs

Graphical User Interfaces (GUIs)

UI Software Organization

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

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

COMP 401 Recitation 8. Observer Pattern

Advanced Java Programming (17625) Event Handling. 20 Marks

Windows and Events. created originally by Brian Bailey

CSE 331 Software Design and Implementation. Lecture 16 Callbacks and Observers

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

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

IT101. Graphical User Interface

Introduction to the JAVA UI classes Advanced HCI IAT351

CSE 331 Final Exam 6/10/14

The init() Method. Browser Calling Applet Methods

HW#1: Pencil Me In Status!? How was Homework #1? Reminder: Handouts. Homework #2: Java Draw Demo. 3 Handout for today! Lecture-Homework mapping.

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

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

CSE1720 Lecture 08; Week 05 Lecture 09 Second level Third level Fourth level Fifth level

CS 2113 Software Engineering

Graphical User Interface (GUI)

Programming Languages 2nd edition Tucker and Noonan"

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

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

Swing from A to Z Some Simple Components. Preface

Java Programming. Computer Science 112

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

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

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

Java GUI Design: the Basics

Dr. Hikmat A. M. AbdelJaber

Charlie Garrod Michael Hilton

Mouse / Keyboard Events & Anonymous Functions. Lecture 19

GUI Components: Part 1

Lab 10: Inheritance (I)

GUI Programming: Swing and Event Handling

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.

Transcription:

CSE 331 Software Design and Implementation Lecture 19 GUI Events Leah Perlmutter / Summer 2018

Announcements

Announcements Quiz 7 due Thursday 8/9 Homework 8 due Thursday 8/9 HW8 has a regression testing component: HW5, 6, 7 tests must pass.

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 Code Exploration! (Bouncing balls app)

Event-driven programming 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,

Kinds of GUI events 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 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

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

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

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

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

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-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

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 button.addactionlistener(new ActionListener(){ public void actionperformed(actionevent e) { model.dosomething() } } );

Example Method call parameter list button.addactionlistener(new ActionListener(){ ); } public void actionperformed(actionevent e) { } model.dosomething()

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() } } );

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

Example ButtonDemo2.java

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 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 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.

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)

Synchronization issues? 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

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 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!

Larger example bouncing balls Download: course website --> lec19 GUI Events --> sim-example.zip To run (command line): > javac BallSimMain.java > java BallSimMain Click to create a new random ball at click location Code exploration Identify buttons and button listeners see BallSimControl.java Notice where repaint is called when the model changes (in BallGraphicsView, called by SimModel.cycle) What would happen if repaint were not called here?

Larger example bouncing balls More code exploration Notice ActionListener in BallSimControl class can call pause, resume, or stop in the model these methods do very little and execute very fast! What would happen if you introduced a 3000 milisecond sleep in the resume method? Identify components of the Model, View, and Controller classes Is there anything you d change? Fix the bug! Balls can get stuck outside frame when you make frame smaller

Announcements

Announcements Quiz 7 due Thursday 8/9 Homework 8 due Thursday 8/9 HW8 has a regression testing component: HW5, 6, 7 tests must pass.