GUI Programming: Swing and Event Handling

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

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

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

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

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

Advanced Java Programming (17625) Event Handling. 20 Marks

The AWT Event Model 9

GUI in Java TalentHome Solutions

GUI Event Handlers (Part I)

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Event Driven Programming

COMPSCI 230. Software Design and Construction. Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

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

PIC 20A GUI with swing

BM214E Object Oriented Programming Lecture 13

Window Interfaces Using Swing Objects

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

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

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

Window Interfaces Using Swing Objects

Class 16: The Swing Event Model

Programming Language Concepts: Lecture 8

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!

Java: Graphical User Interfaces (GUI)

SD Module-1 Advanced JAVA

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

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

Chapter 14. More Swing

SD Module-1 Advanced JAVA. Assignment No. 4

Programming Languages and Techniques (CIS120e)

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

BASICS OF GRAPHICAL APPS

Chapter 1 GUI Applications

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Interacción con GUIs

Dr. Hikmat A. M. AbdelJaber

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

CS11 Java. Fall Lecture 3

Graphical User Interfaces. Comp 152

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

GUI Software Architecture

Introduction to the JAVA UI classes Advanced HCI IAT351

Programming Mobile Devices J2SE GUI

Sri Vidya College of Engineering & Technology

CS 251 Intermediate Programming GUIs: Event Listeners

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

CSE 331 Software Design & Implementation

Swing from A to Z Some Simple Components. Preface

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Java AWT Windows, Text, & Graphics

Java. GUI building with the AWT

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.

Lecture 19 GUI Events

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Basicsof. JavaGUI and SWING

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Graphical Interfaces

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

GUI Components: Part 1

Systems Programming Graphical User Interfaces

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

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

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

CS11 Java. Fall Lecture 4

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

Graphic User Interfaces. - GUI concepts - Swing - AWT

Today. cisc3120-fall2012-parsons-lectiii.3 2

Swing from A to Z Using Focus in Swing, Part 2. Preface

What is Widget Layout? COSC 3461 User Interfaces. Hierarchical Widget Layout. Resizing a Window. Module 5 Laying Out Components

CS 2113 Software Engineering

Come & Join Us at VUSTUDENTS.net

Graphical Interfaces

Part I: Learn Common Graphics Components

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CS Programming Language - JAVA. Fall 2004 Oct.13rd

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Java Programming Lecture 6

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

Laying Out Components. What is Widget Layout?

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

Resizing a Window. COSC 3461: Module 5B. What is Widget Layout? Size State Transitions. What is Widget Layout? Hierarchical Widget Layout.

Lecture 5: Java Graphics

CHAPTER 2. Java Overview

Java GUI Design: the Basics

Unit 7: Event driven programming

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon

Graphical interfaces & event-driven programming

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

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Chapter 6: Graphical User Interfaces

Transcription:

GUI Programming: Swing and Event Handling Sara Sprenkle 1 Announcements No class next Tuesday My Fourth of July present to you: No quiz! Assignment 3 due today Review Collections: List, Set, Map Inner classes AWT, Swing programming Sara Sprenkle - CISC370 2 1

Jar Files Archives of Java files Essentially a Zip of the Java class files Includes a special metadata file with the path META- INF/MANIFEST.MF jar creates a default metadata file, if not specified Why jars? Package code into a neat bundle Easier, faster to download Easier to use Works similarly to tar jar cf myapplication.jar *.class Sara Sprenkle - CISC370 3 Jar file: Metadata Example metadata file that will allow you to execute the JAR with java Manifest-Version: 1.0 Main-Class: MyApplication Note the newline at the end Specifying the metadatafile To create the jar file: jar cmf mymanifest myapplication.jar *.class Run it, using java java -jar myapplication.jar Useful later when we create applets Sara Sprenkle - CISC370 4 2

Using jars Add jar files to CLASSPATH to use classes in jar file Example: adding a jar file to the current classpath variable ($CLASSPATH) setenv CLASSPATH $CLASSPATH:myapplication myapplication.jar Current value of CLASSPATH In Eclipse, you need to Configure Build Path Sara Sprenkle - CISC370 5 Factories A Factory class exists just to create instances of other classes Often produces compatible instances of several related classes Given information about an object, will create the object Allows something else to determine the appropriate customization of object Sara Sprenkle - CISC370 6 3

Factories Information about object Return appropriate instantiation of object Factory May have several different implementations of object to choose from; makes selection Sara Sprenkle - CISC370 7 Factories Tend to have private constructors Cannot make an object using new Use a static method to get the factory Ensures that there is only one factory for all executing classes Factory factory = Factory.getFactory getfactory(); Sara Sprenkle - CISC370 8 4

Reviewing Swing Frame/JFrame Swing Implementation: JFrame Swing naming convention: begin with J Basic window with title Positioning, sizing Set image if iconified How handles closing (setdefaultcloseoperation( setdefaultcloseoperation) Toolkit Get information about screen size Sara Sprenkle - CISC370 9 Reviewing Swing Components Everything you see JFrame is a component Use setvisible to display the frame Windows activation Panels Contain content; useful for layout (more today) Drawing on panels Using different fonts Sara Sprenkle - CISC370 10 5

More GUI components Label Basically, just a string Buttons Like a label but generates events Checkbox Buttons with state about if checked CheckboxGroup Radio buttons - only one can be selected at a time Sara Sprenkle - CISC370 11 More GUI Components Choice Drop-down list FileDialog Opening and saving files List Scrollable Allows multiple selections ScrollPane scrollbars Sara Sprenkle - CISC370 12 6

More GUI Components TextField Single line of text TextArea Multiple lines of text Sara Sprenkle - CISC370 13 Menus MenuBar Thing across top of frame Frame.setMenuBar setmenubar(menubar mb); Menu The dropdown part A sequence of MenuItems Menu is a subclass of MenuItems,, so can have submenus Sara Sprenkle - CISC370 14 7

Combining Components Create a panel with three buttons on it Use panel s add method Sara Sprenkle - CISC370 15 Placement of Components How does the panel know where to place a button? How does the panel know where to place the next button? How does the panel know where to place any component that is added to it? Sara Sprenkle - CISC370 16 8

Layout Managers Java uses a concept of layout managers to place components inside a container The LayoutManager is an object that handles the placement of components When a component is added to a container, through add(), the layout manager decides where to place the component Sara Sprenkle - CISC370 17 The Border Layout Manager Default layout manager of the content pane for JFrame Lets you choose where you want to place each component Center North South East West with respect to the container Sara Sprenkle - CISC370 18 9

Border Layout Regions North West Center East South The edge components are laid out first Center occupies remaining space Sara Sprenkle - CISC370 19 Border Layout Rules The border layout grows all components to fill the available space The flow layout gives each component its preferred size If the container is resized, the edge components are redrawn and the center region size recomputed. To add a component to a container using a border layout, say the content pane of a JFrame: Container contentpane = getcontentpane(); contentpane.add(yellowbutton, BorderLayout.SOUTH); Sara Sprenkle - CISC370 20 10

Adding Components Using a Border Layout Container contentpane = getcontentpane(); contentpane.add(yellowbutton, BorderLayout.SOUTH); If no region of the layout is specified Assumes center region Since border layout grows the component to fit the specified region What happens if we add multiple components, e.g., three buttons, without specifying a region? Sara Sprenkle - CISC370 21 A Border Layout Limitation Three The three button grows to completely fill the center region The one and two buttons were discarded/overwritten by each subsequently added component Sara Sprenkle - CISC370 22 11

The Flow Layout Manager Default layout manager for a panel (not JFrame) What I changed our JFrame to use Lines the components up horizontally until there is no more room in the container Then starts a new row of components If the user resizes the component, the layout manager automatically reflows the components Sara Sprenkle - CISC370 23 The Flow Layout Manager You can choose how to arrange the components in each row Default: center each row Other options: left or right align Change alignment using the setlayout() method causes the panel to use a flow layout manager, with the row components aligned to the left setlayout(new FlowLayout(FlowLayout.LEFT)); Also has hgap and vgap for gaps to put around components Sara Sprenkle - CISC370 24 12

Using Panels w/ Border Layout Panels act as (smaller) containers for UI elements Can be arranged inside a larger panel by a layout manager Use additional panels to address Border Layout problem create a panel add some buttons to it add that panel to the south region of content pane Sara Sprenkle - CISC370 25 Using Additional Panels Get fairly accurate and precise placement of components Use Nested panels with Border layouts - for content panes and enclosing panels Flow layouts - for panels containing the buttons and other UI components FlexibleLayout.java Sara Sprenkle - CISC370 26 13

Changing Layout Managers Any container can use any layout manager Use setlayout() to change layout manager before you add components // sets the layout to a new flow layout manager which // aligns row components to the left and uses a 20 pixel // horizontal separation and 20 pixel vertical separation setlayout(new FlowLayout(FlowLayout.LEFT, 20, 20)); // sets the layout to a new border layout manager which // uses a 45 pixel horizontal separation between components // (regions) and a 20 pixel vertical separation setlayout(new BorderLayout(45, 20)); Sara Sprenkle - CISC370 27 The Grid Layout Manager Divides the container into columns and rows of equal size, which collectively occupy the entire container region Rows and columns are aligned like a spreadsheet When the container is resized, the cells grow and/or shrink Cells always maintain identical sizes Sara Sprenkle - CISC370 28 14

Grid Layout Manager Construction The number and rows to be used in the layout is specified in the construction of the grid layout manager: panel.setlayout(new GridLayout(5, 4)); // 5 rows, 4 cols As with the border and flow layout managers, you can specify a horizontal and vertical separation (between rows and columns): panel.setlayout(new GridLayout(5, 4, 20, 20)); // 5 rows, 4 cols, 20 pixels between rows & between cols Sara Sprenkle - CISC370 29 Adding Components to a Grid Layout Components are added to a grid layout sequentially The first add() adds the component to the 1 st row and 1 st column The second add() adds the component to the 1 st row, 2 nd column. And so forth until the 1 st row is filled in Then the 2 nd row begins with the 1 st column Continues until the entire container is filled Sara Sprenkle - CISC370 30 15

Grid Layout Rules When a component is added to a cell, it is resized to take up the entire cell. This layout manager is quite restrictive but can be useful for some applications Example: to create a row of buttons with identical size make a panel that has a grid layout with one row add a button to each cell set some horiz/vert separation, so the buttons are not touching Sara Sprenkle - CISC370 31 Handling User Interactions Sara Sprenkle - CISC370 32 16

Event Basics An event is generated from an event source and is transmitted to an event listener Event sources allow event listeners to register with them Registered listener is requesting that the event source send its event to the listener when it occurs Think of as mailing list for favorite band but notifies of past releases! All events are objects of event classes All event classes derive from EventObject Sara Sprenkle - CISC370 33 Java / AWT Event Handling Listener object: : implements a listener interface Event source: can register listener objects and send them event objects Event source sends out event objects to all registered listeners when that event occurs. Listener objects use the event object to determine their reaction to the event Sara Sprenkle - CISC370 34 17

Java / AWT Event Handling A listener is registered with an event source by using a line of code similar to eventsourceobject.add addeventlistener( For example eventlistenerobject); ActionListener listener1 =...; JButton button1 = new JButton( Click Me! ); button1.addactionlistener(listener1); listener1 is notified whenever an action event occurs in the button For buttons, an action event is a button click Sara Sprenkle - CISC370 35 Listener Objects A listener object must belong to a class that implements the appropriate interface For buttons, that s ActionListener The listener class must implement the method actionperformed(actionevent event) Sara Sprenkle - CISC370 36 18

Listener Objects and Event Handling When the user clicks the button (button1 in our example), the JButton object generates an ActionEvent object Which makes JButton a what? JButton calls the listener object s actionperformed() method and passes that method the generated event object A single event source can have multiple listeners listening for its events The source calls actionperformed() on each of its listeners Sara Sprenkle - CISC370 37 An Example of Event Handling Suppose we want to make a panel that has three buttons on it Each button has a color associated with it When the user clicks a button, the background color of the panel changes to the corresponding color We need two things: A A panel with three buttons on it Three listener objects, each registered to listen for events on one of the buttons Sara Sprenkle - CISC370 38 19

Event Handling Example Make some buttons and add them to panel public class ColoredBackground extends JFrame { public ColoredBackground() { JButton red = new JButton("Red"); red.setforeground(color.red); JButton yellow = new JButton("Yellow"); yellow.setbackground(color.yellow); JButton blue = new JButton("Blue"); blue.setforeground(color.blue); cp.add(red); cp.add(yellow); cp.add(blue); JButton constructor takes a String (the button s s label) Sara Sprenkle - CISC370 39 Listener Objects Now that we have buttons (event sources), we need listeners An action listener can be any class, as long as it implements the ActionListener interface. Make a new class that implements the interface actionperformed method should set the background color of the panel Sara Sprenkle - CISC370 40 20

Our Listener Class class ColorAction implements ActionListener { public ColorAction(Color c) { backgroundcolor = c; } public void actionperformed(actionevent evt1) { // set panel background color here... } How can we do this? } private Color backgroundcolor; Sara Sprenkle - CISC370 41 Registering Our Listener Class Now that we have a class that listens for the buttons ActionEvents,, we need to create objects and register them with the buttons ColorAction yellowaction = new ColorAction(Color.yellow); ColorAction blueaction = new ColorAction(Color.blue); ColorAction redaction = new ColorAction(Color.red); yellow.addactionlistener(yellowaction); blue.addactionlistener(blueaction); red.addactionlistener(redaction); These are JButtons Sara Sprenkle - CISC370 42 21

Registering Our Listener Class When a user clicks the button with the label Yellow,, the yellow JButton object generates an ActionEvent passes this event object to the yellowaction s actionperformed() method method can then set the background color of the frame Any problems? Sara Sprenkle - CISC370 43 The Listener Class & the Frame The ColorAction objects have no access to the frame How can they change the background color? There are two possible solutions: Add a frame instance field to the ColorAction class and set it in the constructor ColorAction object knows which frame it is associated with and can call the appropriate method of that frame to change its background color Make ColorAction an inner class of ButtonPanel1 Sara Sprenkle - CISC370 44 22

Listener as an Inner Class Let s s make it an inner class class ColoredBackground extends JFrame {... private class ColorAction implements ActionListener {... public void actionperformed(actionevent evt) { setbackground(backgroundcolor); repaint(); } private Color backgroundcolor; } } Sara Sprenkle - CISC370 45 The actionperformed() Method public void actionperformed(actionevent evt) { setbackground(backgroundcolor); repaint(); } ColorAction class does not have setbackground() or repaint() methods Since it is an inner class of ColoredBackground,, it can directly access that class instance fields and methods Inner class calls the outer class s s method using its own private inner data (backgroundcolor( backgroundcolor) Then it calls the outer class s repaint() method Redraw the frame Sara Sprenkle - CISC370 46 23

Event Listeners as Inner Classes A common and beneficial practice Event listener objects typically need to do something to other objects when their corresponding event occurs It is often possible to place the listener class inside the class whose state the listener should modify It makes good sense from an OOP design standpoint Not violating encapsulation rules also makes things easier Sara Sprenkle - CISC370 47 A Different Listener Approach Any object of a class that implements ActionListener can listen for action events from a source we could make our ColoredBackground class listen for its own buttons events implement the interface and do the correct registering with the buttons Sara Sprenkle - CISC370 48 24

A Different Listener Approach class ColoredBackground2 extends JFrame implements ActionListener { public ColoredBackground2() {... yellow.addactionlistener(this); blue.addactionlistener(this); red.addactionlistener(this); }... public void actionperformed(actionevent evt) { // set background color... } } Sara Sprenkle - CISC370 49 A Different Listener Approach The ColoredBackground method actionperformed() will run whenever any of the buttons is clicked How do we find out which button was pressed? public void actionperformed(actionevent evt) { Object source = evt.getsource(); // gets the source that generates this event } if (source == yellow)... else if (source == blue)... else if (source == red)... Why ==, not equals()? Sara Sprenkle - CISC370 50 25

Which way is better? The inner class approach makes sense from an OOP design point Each event source gets its own listener, which can directly modify the panel as it needs to do Having the panel itself listen is much more straightforward Since the panel needs to change, have it listen! But, the handling method must determine the source of the event and switch its behavior Consider: How easy to add additional event sources for each case? Sara Sprenkle - CISC370 51 Which Way is Better? Neither way is better. better. If a container has multiple UI components that generate events, the container listening for and handling them all gets really confusing and challenging Inner classes make sense Somewhat confusing at first Great benefits We will tend to use the inner class listeners Sara Sprenkle - CISC370 52 26

Simplification of our Event Handlers For each button, we do four things: Construct the button with a label string Add the button to the panel Construct an action listener with the appropriate color Register that listener with the button Make a method that does this for us to simplify the code Sara Sprenkle - CISC370 53 Simplification of our Event Handlers void makebutton(string label, Color backgroundcolor) { JButton button = new JButton(label); add(button); ColorAction action = new ColorAction(backgroundColor); button.addactionlistener(action); } Makes the ColoredBackground constructor much simpler public ColoredBackground() { makebutton( Yellow,Color.yellow); makebutton( Blue,Color.blue); makebutton( Red,Color.red); } Sara Sprenkle - CISC370 54 27

One More Step We only use the ColorAction class in the makebutton() method How can we further simplify the code? Sara Sprenkle - CISC370 55 One More Step Make the ColorAction class an anonymous inner class only use this class at one point define it on the fly Sara Sprenkle - CISC370 56 28

An Anonymous Class Listener void makebutton(string label, final Color bgcolor) { JButton button = new JButton(label); add(button); button.addactionlistener( new ActionListener() { public void actionperformed(actionevent evt) { setbackground(bgcolor); repaint(); } } ); } Sara Sprenkle - CISC370 57 Window Events Not every event is as simple to handle as a button click When a user closes a window, the window simply stops being displayed Program will not end Suppose we want our program to end when a certain frame is closed Closing a frame is a window event in contrast to an action event Sara Sprenkle - CISC370 58 29

Window Events To catch window events, you need to create an object of a class that implements the WindowListener interface WindowListener object is registered with the frame using the frame s addwindowlistener() method Note the parallels with action events change the type of listener and register it using a different (but similar) method call Sara Sprenkle - CISC370 59 The WindowListener Interface The WindowListener interface contains seven methods One for each type of window event A class that implements WindowListener must have all seven methods Sara Sprenkle - CISC370 60 30

The WindowListener Interface public interface WindowListener { void windowopened(windowevent e); void windowclosing(windowevent e); void windowclosed(windowevent e); void windowiconified(windowevent e); void windowdeiconified(windowevent e); void windowactivated(windowevent e); void windowdeactivated(windowevent e); } Sara Sprenkle - CISC370 61 Implementing a WindowListener To create an object that can listen for window events on a frame and end the program when the frame is closed class Terminator implements WindowListener { public void windowclosing(windowevent evt) { System.exit(0); } For JFrame s use setdefaultclosedoperation } public void windowopened(windowevent e) {} public void windowclosed(windowevent e) {} public void windowiconified(windowevent e) {} public void windowdeiconified(windowevent e) {} public void windowactivated(windowevent e) {} public void windowdeactivated(windowevent e) {} Sara Sprenkle - CISC370 62 31

Adapter Classes Typing the code for the six methods that don t t do anything is somewhat tedious Most AWT listener interfaces have a corresponding adapter class Class that implements all of the methods in the interface but does nothing inside all of them. There are no adapter classes for AWT interfaces with only one method (such as ActionListener) Sara Sprenkle - CISC370 63 Adapter Classes If you want an WindowListener class that does nothing with six of the seven window events, but ends the program when the window is closed create a new class that extends the WindowAdapter class and override the method(s) you are interested in When could extending a class be a problem? How big of a concern is that for this specific case/type of class? Sara Sprenkle - CISC370 64 32

Extending an Adapter Class We can now redefine our Terminator class in much less code class Terminator extends WindowAdapter { public void windowclosing(windowevent evt) { System.exit(0); } // all other methods are the same as in // WindowAdapter, all do nothing. } Sara Sprenkle - CISC370 65 Registering a WindowListener Now, we can register our Terminator class to listen for window events. Assuming that our main window frame is named frame1 (e.g., if frame1 is closed the program should exit) WindowListener listener1 = new Terminator(); frame1.addwindowlistener(listener1); Sara Sprenkle - CISC370 66 33

One Step Farther Using the WindowAdapter class instead of writing out all the methods in the WindowListener interface is nice, but we can go one step farther frame1.addwindowlistener( new WindowAdapter() { public void windowclosing(windowevent evt) { System.exit(0); } } ); Sara Sprenkle - CISC370 67 One Step Farther This code does five things: Defines a new class without a name that extends the WindowAdapter class Adds a windowclosing() method to that anonymous class (the exits the program) Inherits the remaining six empty methods from the WindowAdapter class Creates an object of this new class This object also does not have a name Passes this new no-name object to the addwindowlistener method of frame1 Sara Sprenkle - CISC370 68 34

The AWT Event Hierarchy There are 10 different types of events in the AWT Sara Sprenkle - CISC370 69 AWT Event Types Semantic Events Four types of semantic events an event that expresses what a user did, such as clicking a button. ActionEvent button click, menu selection, selecting a list item, pressing ENTER in a text field AdjustmentEvent user adjusted a scroll bar ItemEvent user made a selection from a set of checkboxes or list items TextEvent the contents of a text field or text area were changed Sara Sprenkle - CISC370 70 35

AWT Event Types Low-Level Events 6 types low-level events An event that makes a semantic event possible ComponentEvent component was changed (resized, moved, shown, etc ) KeyEvent a key was pressed or released MouseEvent the mouse was moved, dragged, or a button was pressed FocusEvent component got or lost focus WindowEvent window was activated, closed, etc. ContainerEvent component was added or deleted. Sara Sprenkle - CISC370 71 AWT Event Types Example: adjusting a scrollbar is a semantic event made possible by some low-level events such as dragging the mouse As a general rule, low-level events cause semantic events to happen Sara Sprenkle - CISC370 72 36

Event Listeners 11 interfaces that correspond to AWT event listeners: ActionListener, AdjustmentListener, ItemListener, TextListener, ComponentListener, ContainerListener, FocusListener, KeyListener, MouseListener, MouseMotionListener, and WindowListener. Sara Sprenkle - CISC370 73 Event Listeners See Javadocs for interfaces and all the methods that are in them Each listener interface with more than one method has a corresponding adapter class implements the interface with all empty methods Sara Sprenkle - CISC370 74 37

Components and ComponentEvents A component is a user interface element such as a button, textfield, or scrollbar All low-level events inherit from ComponentEvent getcomponent() returns the component that originated the event same thing as getsource(), but it returns the object as a Component and not an Object For example, if a key event was generated because of an input into a text field, then getcomponent returns a reference to that text field Sara Sprenkle - CISC370 75 Containers and ContainerEvents A container is a screen area or component can contain components, such as a window or a panel A ContainerEvent is generated whenever a component is added or removed from the container supports the programming of dynamically- changing user interfaces Sara Sprenkle - CISC370 76 38

FocusEvents A FocusEvent is generated when a component gains or loses focus FocusListener must implement two methods: focusgained(): called whenever the event source the listener is registered with gains the focus focuslost(): called whenever the event source the listener is registered with loses the focus Sara Sprenkle - CISC370 77 KeyEvents A KeyEvent is generated when a key is pressed or released. A KeyListener must implement three methods: keypressed() will run whenever a key is pressed keyreleased() will run whenever that key is released keytyped() combines the two it runs when the key is pressed and then released, and signifies a keystroke Sara Sprenkle - CISC370 78 39

KeyEvents With what type of object does a KeyListener register with? What is an event source for a KeyEvent? Any Component can be an event source for a KeyEvent A component generates a KeyEvent whenever a key is typed in that component For example, if the user types into a textfield, that textfield will generate the appropriate KeyEvents Sara Sprenkle - CISC370 79 MouseEvents MouseEvents are generated like KeyEvents mousepressed() mousereleased() mouseclicked() You can ignore the first two if you only care about clicking Call getclickcount() on a MouseEvent object to distinguish between a single and a double click You can distinguish between the various mouse buttons by calling getmodifiers() on a MouseEvent object E.g., middle button Sara Sprenkle - CISC370 80 40

MouseEvents MouseEvents are also generated when the mouse pointer enters and leaves components (mouseentered() and mouseexited()). All of those methods are part of the MouseListener interface The actual movement of the mouse is handled with the MouseMotionListener interface. most applications only care about where you click and not how and where you move the mouse pointer around Sara Sprenkle - CISC370 81 Model - Viewer - Controller (MVC) A common design pattern for designing GUIs Design Pattern: proven way to design something Separate Model: application data View: graphical representation Controller: input processing Controller Modifies Model Notifies View Sara Sprenkle - CISC370 82 41

Model-Viewer-Controller Can have multiple viewers and controllers Can modify one component without affecting others Sara Sprenkle - CISC370 83 Model Code that carries out some task Nothing about how view presented to user Purely functional Must be able to register views and notify views of changes Sara Sprenkle - CISC370 84 42

Multiple Views Provides GUI interface components for model User manipulates view Informs controller of change Example of multiple views: spreadsheet data Rows/columns in spreadsheet Pie chart Sara Sprenkle - CISC370 85 Multiple Controllers Update model as user interacts with view Calls model s mutator methods Views are associated with controllers Sara Sprenkle - CISC370 86 43

Designing a Card Game What is the Model View(s) Solitaire? Poker? Controller(s) Sara Sprenkle - CISC370 87 Project 1: Freecell Part 1: Understand code base Given a Solitaire code base, Javadocs (API), example code that uses code base Compile, use, and understand Part 2: Use code base to implement Freecell GUI, Event handling Implementing/Enforcing the Freecell rules Sara Sprenkle - CISC370 88 44

Project 1: Freecell Submission: printed, electronic, and demo Submission due Thursday, July 13 New: Test Plan Individual classes, whole application Documentation: describe design decisions Demo with Ke Schedule demos Monday-Wednesday of following week (Project 2 demos with Sara) Script file doesn t t make as much sense Sara Sprenkle - CISC370 89 45