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!