CSE 331 Software Design and Implementation

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

Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Event Handling Events and Listeners Timers and Animation.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
Object-Oriented Analysis and Design
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Welcome to CIS 083 ! Events CIS 068.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
(c) University of Washington08-1 CSC 143 Models and Views Reading: Ch. 18.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Event Driven Programming, The.
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.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
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.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
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.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Concurrent Programming and Threads Threads Blocking a User Interface.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
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 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,
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.
Lesson 28: More on the GUI button, frame and actions.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
GUI Programming using Java - Event Handling
Events and Event Handling
Chapter 14 Event-Driven Programming
CompSci 230 S Programming Techniques
CHAPTER Reacting to the user.
Applets.
Appendix I GUI Components and Event Handling
A First Look at GUI Applications
Event loops 16-Jun-18.
CSE 331 Software Design & Implementation
CSE 331 Software Design & Implementation
Lecture 28 Concurrent, Responsive GUIs
CSE 331 Software Design and Implementation
Programming in Java Event Handling
Ellen Walker Hiram College
GUI Event Handling Nithya Raman.
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Event Driven Programming
EE 422C Java FX.
Chapter 15 Event-Driven Programming and Animations
CSE 331 Software Design and Implementation
Event loops.
Event loops 17-Jan-19.
Event loops 17-Jan-19.
Events, Event Handlers, and Threads
Constructors, GUI’s(Using Swing) and ActionListner
Event loops 8-Apr-19.
Model, View, Controller design pattern
Event loops.
CSE 331 Software Design & Implementation
Event loops.
Event loops 19-Aug-19.
Presentation transcript:

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() } ); I updated the colors on this slide to be more colorblind-friendly (https://www.color-blindness.com/coblis-color-blindness-simulator/)

Example Method call parameter list button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { model.doSomething() } ); Method call parameter list

Example Class or interface being extended/implemented (can include constructor parameters) button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { model.doSomething() } ); new expression to create class instance Method call parameter list

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

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) 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. actionPerformed(e) - calling paintComponent incorrectly could introduce bugs that you don’t notice right away, which will make debugging harder when they cause problems later. repaint() paintComponent(g)

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 Note: this is probably too many suggestions to do in class.

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.