GUI Event-Driven Programming



Similar documents
GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

CS 335 Lecture 06 Java Programming GUI and Swing

Programming with Java GUI components

Event processing in Java: what happens when you click?

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Swing. A Quick Tutorial on Programming Swing Applications

Assignment # 2: Design Patterns and GUIs

core 2 Handling Mouse and Keyboard Events


GUI Components: Part 2

Mouse Event Handling (cont.)

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Providing Information (Accessors)

Automated Data Collection for Usability Evaluation in Early Stages of Application Development

The Basic Java Applet and JApplet

Extending Desktop Applications to the Web

java.applet Reference

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

GUI and Web Programming

Model-View-Controller (MVC) Design Pattern

Using A Frame for Output

Developing GUI Applications: Architectural Patterns Revisited

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

Java Mouse and Keyboard Methods

Fundamentals of Java Programming

How Scala Improved Our Java

JiST Graphical User Interface Event Viewer. Mark Fong

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Animations in DrRacket

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Lecture VII JAVA SWING GUI TUTORIAL

@ - Internal # - Online TH PR OR TW TOTAL HOURS # @ 175

During the process of creating ColorSwitch, you will learn how to do these tasks:

Java SE 8 Programming

Essentials of the Java(TM) Programming Language, Part 1

Desktop, Web and Mobile Testing Tutorials

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

1 Hour, Closed Notes, Browser open to Java API docs is OK

MiniDraw Introducing a framework... and a few patterns

Payroll. 4. Print Checks. Table of Contents Print Checks...2 All...3 Department...4 Print Single Posting...5

CREATE AN ANIMATED AQUARIUM IN POWERPOINT

Schueler-Organisiertes Lernen am Beispiel von Grafischen Benutzer-Schnittstellen in Java Tag der Offenen Tür - GTS 2008

How To Insert Hyperlinks In Powerpoint Powerpoint

MA-WA1920: Enterprise iphone and ipad Programming

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Table of Contents. Adding Build Targets to the SDK 8 The Android Developer Tools (ADT) Plug-in for Eclipse 9

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

COMMUNITY COLLEGE OF CITY UNIVERSITY CITY UNIVERSITY OF HONG KONG

Mobile App Tutorial Animation with Custom View Class and Animated Object Bouncing and Frame Based Animation

Visual Basic Programming. An Introduction

TATJA: A Test Automation Tool for Java Applets

: provid.ir

Event-Driven Programming

Java EE Web Development Course Program

Blender Notes. Introduction to Digital Modelling and Animation in Design Blender Tutorial - week 9 The Game Engine

Syllabus for CS 134 Java Programming

Why Threads Are A Bad Idea (for most purposes)

WA2262 Applied Data Science and Big Data Analytics Boot Camp for Business Analysts. Classroom Setup Guide. Web Age Solutions Inc.

Computing Concepts with Java Essentials

While Loops and Animations

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

DiskBoss. File & Disk Manager. Version 2.0. Dec Flexense Ltd. info@flexense.com. File Integrity Monitor

Microsoft Excel 2007 Consolidate Data & Analyze with Pivot Table Windows XP

Essentials of the Java Programming Language

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

To Java SE 8, and Beyond (Plan B)

VAASAN AMMATTIKORKEAKOULU UNIVERSITY OF APPLIED SCIENCES. Xiaoling Yu IMPLEMENTATION OF A SECURE SHELL FILE TRANSFER PROGRAM IN JAVA

Microsoft Access 3: Understanding and Creating Queries

ERserver. iseries. Work management

Tutorial Reference Manual. Java WireFusion 4.1

How To Write A Program For The Web In Java (Java)

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Configuring the Server(s)

What is Android? originally purchased from Android, Inc. in 2005

Input and Interaction. Project Sketchpad. Graphical Input. Physical Devices. Objectives

About XML in InDesign

Responders: Language Support for Interactive Applications

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

PloneSurvey User Guide (draft 3)

Konzepte objektorientierter Programmierung

GLOBAL CROSSING READY-ACCESS WEB MEETING. User Guide GETTING STARTED FEATURES INSTALLING THE JAVA PLUG-IN 9 SYSTEM REQUIREMENTS 9

Introduction. Inserting Hyperlinks. PowerPoint 2010 Hyperlinks and Action Buttons. About Hyperlinks. Page 1

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

Munis Payroll Entry Instructions

Notepad++ The COMPSCI 101 Text Editor for Windows. What is a text editor? Install Python 3

KIVY - A Framework for Natural User Interfaces

Voice Driven Animation System

How to set up a scoring algorithm and automatic triggers for Qualtrics measures

Java Classes. GEEN163 Introduction to Computer Programming

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Developing NFC Applications on the Android Platform. The Definitive Resource

BallBounce: A simple game app

Web Application Testing. Web Performance Testing

Android Application Development Course Program

Advanced Network Programming Lab using Java. Angelos Stavrou

Paper Designing Web Applications: Lessons from SAS User Interface Analysts Todd Barlow, SAS Institute Inc., Cary, NC

Java (12 Weeks) Introduction to Java Programming Language

Set up Technician for Field Service. User Guide

Transcription:

GUI Event-Driven Programming CSE 331 Software Design & Implementation Slides contain content by Hal Perkins and Michael Hotan 1

Outline User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction between UI and program threads 2

Event-driven programming The main body of the program is an event loop. Abstractly: do { e = getnextevent(); process event e; } while (e!= quit); 3

Event-driven programming Event-driven programming: A style of coding where a program's overall flow of execution is dictated by events. The program loads, then waits for user input events. As each event occurs, the program runs particular code to respond. The overall flow of what code is executed is determined by the series of events that occur Contrast with application-or algorithm-driven control where program expects input data in a pre-determined order and timing Typical of large non-gui applications like web crawling, payroll, batch simulation

Graphical events event: An object that represents a user's interaction with a GUI component; can be "handled" to create interactive components. listener: An object that waits for events and responds to them. To handle an event, attach a listener to a component. The listener will be notified when the event occurs (e.g. button click).

Kinds of GUI events Mouse move/drag/click, mouse button press/release Keyboard: key press/release, sometimes with modifiers like shift/control/alt/meta/cokebottle Touchscreen finger tap/drag Joystick, drawing tablet, other device inputs Window resize/minimize/restore/close Network activity or file I/O (start, done, error) Timer interrupt (including animations) 6

EventObject represents an event import java.awt.event.*; EventObject AWTEvent (AWT) ActionEvent TextEvent ComponentEvent FocusEvent WindowEvent InputEvent KeyEvent MouseEvent An action that has occurred on a GUI component button/menu/ checkbox/text box/ keyboard 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 mouse move/drag/ click/wheel

Action events action event: An action that has occurred on a GUI component. The most common, general event type in Swing. Caused by: button or menu clicks, check box checking / unchecking, pressing Enter in a text field,... Represented by a class named ActionEvent Handled by objects that implement interface ActionListener

Handling events in Java Swing/AWT GUI widgets can generate events (in response to button clicks, menu picks, key press, etc.) Handled using observer pattern. Standard observer pattern: Object wishing to handle event is an Observer Object that generates events is an Observable Observer registers with the observable When an event happens, observable calls a method (update) in each observer may notify multiple observers 9

Implementing a listener public class MyClass implements ActionListener { public void actionperformed(actionevent event) { code to handle the event; } } JButton and other graphical components have this method: /** Attaches the given listener to be notified of clicks and events that occur on this component. */ public void addactionlistener(actionlistener al)

EventListener type hierarchy import java.awt.event.*; EventListener AWTEventListener ActionListener has method actionperformed() TextListener ComponentListener FocusListener WindowListener KeyListener has method keypressed() MouseListener has method mouseclicked() MouseMotionListener has method mousedragged() When an event, occurs the appropriate method specified in the interface is called An event object is passed as a parameter to the event listener method

JButton a clickable region for causing actions to occur public JButton(String text) Creates a new button with the given string as its text. public String gettext() Returns the text showing on the button. public void settext(string text) Sets button's text to be the given string.

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 13

Which button is which? Q: A single button listener often handles several buttons. How to tell which is which? A: an ActionEvent has a getactionevent method that returns (for a button) the action command string Default is the button name, but usually better to set it to a particular string that will remain the same inside the program code even if the UI is changed or translated. See button example. Similar mechanisms to decode other events 14

Inner classes nested class: A class defined inside of another class. Two varieties: static nested class, and inner classes Usefulness: Inner classes are hidden from other classes (encapsulated). Inner objects can access/modify the fields of their outer object. Event listeners are often defined as nested classes inside a GUI.

Nested class syntax // Enclosing outer class public class OuterName {... } // Instance nested class (= inner class) // A different class for each instance of OuterName private class InnerName {... } // Static nested class // One class, shared by all instances of OuterName // (syntactic sugar for a top-level class) static private class NestedStaticName {... } If private, only the outer class can see the nested class or make objects of it. Each inner object is associated with the outer object that created it, so it can access/modify that outer object's methods/fields. If necessary, can refer to outer object as OuterName.this

Use-once classes ButtonDemo1.java defines a class that is only used 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? Solution: anonymous inner classes 17

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 base class 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) 18

Anonymous class syntax Method call parameter list new expression to create class instance Base class or interface being extended (constructor parameters ok if needed) button.addactionlistener(new ActionListener(){ ); } public void actionperformed(actionevent e) { } model.dosomething() Implementation of method for this anonymous class Java 8 lambdas (function closures) improve the syntax Brackets surrounding new class definition 19

Example ButtonDemo2.java 20

Program thread and UI thread The program and user interface run in concurrent threads All UI actions happen in the UI thread even when they execute callbacks to code like actionlistener, etc. defined in your program After event handling and related work, you may call repaint() if paintcomponent() needs to run. Do not 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 21

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

Working in the UI thread Event handlers usually should not do a lot of work If the event handler does a lot of computing, the user interface will appear to freeze up 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) 23

Synchronization issues? Yes, there can be synchronization problems Not usually an issue in well-behaved programs, but can happen if you work at it (deliberately or not) 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 ever call paintcomponent directly (Have we mentioned you should never call paintcomponent? And don t create a new Graphics object either.) 24

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: Poor 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 Have fun! 25