GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Similar documents
Unit 7: Event driven programming

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

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

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

The AWT Event Model 9

GUI in Java TalentHome Solutions

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

Programming Languages and Techniques (CIS120)

Programming Mobile Devices J2SE GUI

Programming Languages and Techniques (CIS120)

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

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

Class 16: The Swing Event Model

Advanced Java Programming (17625) Event Handling. 20 Marks

Programming Languages and Techniques (CIS120)

Graphical User Interfaces 2

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

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!

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

Programming Languages and Techniques (CIS120)

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

G51PRG: Introduction to Programming Second semester Applets and graphics

Lecture 19 GUI Events

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

CSE 331 Software Design & Implementation

Programming graphics

Computer Science 210: Data Structures. Intro to Java Graphics

GUI Event Handlers (Part I)

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Bean Communication. COMP434B Software Design. Bean Communication. Bean Communication. Bean Communication. Bean Communication

Graphical User Interface (GUI)

COMPSCI 230. Software Design and Construction. Swing

User interfaces and Swing

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

Programming Languages and Techniques (CIS120)

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

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

CS2110. GUIS: Listening to Events

SD Module-1 Advanced JAVA

Graphical User Interfaces 2

SD Module-1 Advanced JAVA. Assignment No. 4

Chapter 14: Applets and More

8/23/2014. Chapter Topics. Introduction to Applets. Introduction to Applets. Introduction to Applets. Applet Limitations. Chapter 14: Applets and More

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

Graphical User Interfaces 2

Event Driven Programming

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

Chapter 14: Applets and More

GUI Software Architecture

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CS2110. GUIS: Listening to Events. Anonymous functions. Anonymous functions. Anonymous functions. Checkers.java. mainbox

Graphical User Interface (GUI)

CS2110. GUIS: Listening to Events

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

Cheng, CSE870. More Frameworks. Overview. Recap on OOP. Acknowledgements:

CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions. Anonymous functions. Anonymous functions. Anonymous functions

Designing and Writing a Program. Divide and Conquer! The Design-Code-Debug Cycle. Documentation is Code. Pair Programming 3/8/2012

Java Coordinate System

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

CS 2113 Software Engineering

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Course: CMPT 101/104 E.100 Thursday, November 23, 2000

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.

Java AWT Windows, Text, & Graphics

Java Programming Lecture 6

Chapter 1 GUI Applications

DESIGNING, CODING, AND DOCUMENTING

Programming Languages and Techniques (CIS120)

BM214E Object Oriented Programming Lecture 13

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

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

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

PESIT Bangalore South Campus

GUI Event Handlers (Part II)

Systems Programming Graphical User Interfaces

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Java Event Handling -- 1

14.2 Java s New Nimbus Look-and-Feel 551 Sample GUI: The SwingSet3 Demo Application As an example of a GUI, consider Fig. 14.1, which shows the SwingS

Packages: Putting Classes Together

Windows and Events. created originally by Brian Bailey

Lecture 5: Java Graphics

Announcements. Java Graphics. Exceptions. Java Odds & Ends

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

To gain experience using GUI components and listeners.

Handling Mouse and Keyboard Events

GUI Programming: Swing and Event Handling

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

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

CS 251 Intermediate Programming GUIs: Event Listeners

Object Orientated Programming in Java. Benjamin Kenwright

Come & Join Us at VUSTUDENTS.net

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

BASICS OF GRAPHICAL APPS

CSE 331. Event- driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Introduction to the JAVA UI classes Advanced HCI IAT351

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Transcription:

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain other components frames, panels, dialog boxes,... Layout managers: control placement and sizing of components Helper classes E.g. Graphics, Color, Font, FontMetrics, Dimension,... Dynamics: user interactions Events E.g. button-press, mouse-click, key-press,... Listeners an object that listens for certain events Handlers a method that execute an event response

Dynamics Overview 3 Dynamics = causing and responding to actions What actions? Called events: mouse clicks, mouse motion, dragging, keystrokes We would like to write code (a handler) that is invoked when an event occurs so that the program can respond appropriately In Java, you can intercept events by providing an object that hears the event a listener What objects do we need to know about? Events Listeners Handlers

4 Button pushing example

The Java Event Model 6 Timeline User or program does something to a component clicks on a button, resizes a window,... Java issues an event object describing the event A special type of object (a listener) hears the event The listener has a method that handles the event The handler does whatever the programmer programmed What you need to understand Events: How components issue events Listeners: How to make an object that listens for events Handlers: How to write a method that responds to an event

Events: How your application learns when something interesting happens 7 Basic idea: You register a listener and Java calls it The argument is an event : a normal Java object Events are normally created by the Java runtime system You can create your own, but this is unusual Normally events are associated with a component Most events are in java.awt.event and javax.swing.event All events are subclasses of AWTEvent ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent HierarchyEvent InputEvent InputMethodEvent InvocationEvent ItemEvent KeyEvent MouseEvent MouseWheelEvent PaintEvent TextEvent WindowEvent

Types of Events 8 Each Swing Component can generate one or more types of events The type of event depends on the component Clicking a JButton creates an ActionEvent Clicking a JCheckbox creates an ItemEvent The different kinds of events include different information about what has occurred All events have method getsource() which returns the object (e.g., the button or checkbox) on which the Event initially occurred An ItemEvent has a method getstatechange() that returns an integer indicating whether the item (e.g., the checkbox) was selected or deselected

Event Listeners 9 ActionListener, MouseListener, WindowListener,... Listeners are Java interfaces Any class that implements that interface can be used as a listener To be a listener, a class must implement the interface Example: an ActionListener must contain a method public void actionperformed(actionevent e)

Implementing Listeners 10 Which class should be a listener? Java has no restrictions on this, so any class that implements the listener will work Class must have access to the necessary state to respond appropriately to the event (button push example: listener must be able to increase count) Typical choices Top-level container that contains whole GUI public class GUI implements ActionListener Inner classes to create specific listeners for reuse private class LabelMaker implements ActionListener Anonymous classes created on the spot b.addactionlistener(new ActionListener() {...});

Listeners and Listener Methods 11 When you implement an interface, you must implement all the interface s methods Interface ActionListener has one method: void actionperformed(actionevent e) Interface MouseListener has five methods: void mouseclicked(mouseevent e) void mouseentered(mouseevent e) void mouseexited(mouseevent e) void mousepressed(mouseevent e) void mousereleased(mouseevent e) Interface MouseMotionListener has two methods: void mousedragged(mouseevent e) void mousemoved(mouseevent e)

Registering Listeners 12 How does a component know which listener to use? You must register the listeners This connects listener objects with their source objects Syntax: component.addtypelistener(typelistener listener) Where is Type is replaced by event type. You can register as many listeners as you like

Listener examples 12 ListenerExample0.java One event source (button), no listener ListenerExample1.java One event source (button), one listener (frame) ListenerExample2.java Multiple event sources (buttons), one event listener (frame) ListenerExample3.java Multiple event sources (buttons), multiple listeners (frame, button)

Design Patterns 28 Introduced in 1994 by Gamma, Helm, Johnson, Vlissides (the Gang of Four ) Identified 23 classic software design patterns in OO programming More than 1/2 million copies sold in 14 languages

Observer Pattern 32 Observable changes from time to time is aware of Observers, other entities that want to be informed when it changes but may not know (or care) what or how many Observers there are Observer interested in the Observable want to be informed when the Observable changes

Observer Pattern 33 Issues does the Observable push information, or does the Observer pull it? (e.g., email vs newsgroup) whose responsibility is it to check for changes? publish/subscribe paradigm Observable Observers

Observer Pattern 34 public interface Observer<E> { void update(e event); } public class Observable<E> { private Set<Observer<E>> observers = new HashSet<Observer<E>>(); boolean changed; void addobserver(observer<e> obs) { observers.add(obs); } void removeobserver(observer<e> obs) { observers.remove(obs); } } void notifyobservers(e event) { if (!changed) return; changed = false; for (Observer<E> obs : observers) { obs.update(event); } }

Observer Pattern in GUIs 17 Observable: Any component that can produce events (e.g., JButton) Observer: Any object that wants to handle an event Adding observer: Component adds a listener Notifying observer When a event occurs, the listener method (e.g., actionperformed) is called on each observer object

Example of handling mouse events 18 AdapterExample0.java Frame listens for mouse entries. Implements mouse listener interface but most method bodies empty. AdapterExample1.java Uses an inner class that extends MouseAdapter to count number of mouse entries AdapterExample2.java Uses an anonymous inner class that extends MouseAdapter to count number of mouse entries

Adapters 16 Some listeners (e.g., MouseListener) have lots of methods; you don t always need all of them For instance, you may be interested only in mouse clicks For this situation, Java provides adapters An adapter is a predefined class that implements all the methods of the corresponding Listener Example: MouseAdapter is a class that implements all the methods of interfaces MouseListener and MouseMotionListener The adapter methods do nothing To easily create your own listener, you extend the adapter class, overriding just the methods that you actually need

Adapter design pattern 20 Problem: Client code expects InterfaceA But class C implements InterfaceB (similar to InterfaceA) Adapter: changes the interface of C so that it appears to have InterfaceA Implementation 1: create a wrapper class D D implements InterfaceA D contains an instance of C Method bodies of D simply call methods of C Implementation 2: inherit from adapter class D C overrides methods of D that it knows how to handle For other methods, accept default behavior given by D

Adapter Examples 21 MouseAdapter (follows implementation 2) Need a class that implements MouseListener Our class only implements mouseentered MouseAdapter implements MouseListener with empty method bodies Our class extends MouseAdapter but only overrides mouseentered StackBackedList (follows implementation 1) Need a Stack (push, pop, peek) Have a LinkedList (add, remove, get, etc.) Create a class StackBackedList that contains a LinkedList object and implements push by calling add, etc.

Anonymous classes 22 A class that has no name Method bodies defined on the fly at the moment of creation Must be subtype of an existing interface or class See example for the (awkward, ugly) syntax

Notes on Events and Listeners 18 A single component can have many listeners Multiple components can share the same listener Can use event.getsource() to identify the component that generated the event For more information on designing listeners, see http:// java.sun.com/docs/books/tutorial/ uiswing/events/ For more information on designing GUIs, see http://java.sun.com/docs/books/ tutorial/uiswing/

GUI Drawing and Painting 25 For a drawing area, extend JPanel and override the method public void paintcomponent(graphics g) paintcomponent contains the code to completely draw everything in your drawing panel Do not call paintcomponent directly instead, request that the system redraw the panel at the next convenient opportunity by calling mypanel.repaint() repaint() requests a call paintcomponent() soon repaint(ms) requests a call within ms milliseconds Avoids unnecessary repainting 16ms is a reasonable value

Java Graphics 26 The Graphics class has methods for colors, fonts, and various shapes and lines setcolor(color c) drawoval(int x, int y, int width, int height) filloval(int x, int y, int width, int height) drawline(int x1, int y1, int x2, int y2) drawstring(string str, int x, int y) Take a look at java.awt.graphics (for basic graphics) java.awt.graphics2d (for more sophisticated control) The 2D Graphics Trail: http://java.sun.com/docs/books/tutorial/2d/ examples on the web site

Events and Graphics 26 In a drawing or painting application, when user drags mouse the canvas should respond appropriately -- for example, by painting a line Painting happens in paintcomponent What is painted can depend on the state of the object Can use state to keep track of what should be painted When event occurs, update state add then call repaint()which, in turns, calls paintcomponent

Painting Event Examples 27 Scribble.java Scribble2.java MovingSquare.java

Your turn 28 How would you implement the MovingSquare? What is painted on screen? What events needs to be handled? Hint: there are 3 How does an event affect what gets painted on the screen? Since painting happens in paintcomponent and event handling happens elsewhere, need to use variables (i.e., state) to share information about event. What variables do you need? Hint: at least 3, my implementation has 5!