Class 16: The Swing Event Model

Similar documents
Class 14: Introduction to the Swing Toolkit

AP CS Unit 11: Graphics and Events

MIT AITI Swing Event Model Lecture 17

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

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

Class 27: Nested Classes and an Introduction to Trees

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

1.00 Lecture 14. Lecture Preview

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

PIC 20A GUI with swing

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Part I: Learn Common Graphics Components

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

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

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Graphical User Interface (GUI)

Unit 7: Event driven programming

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

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

Lecture 19 GUI Events

CS 251 Intermediate Programming GUIs: Event Listeners

Agenda. Container and Component

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

CSE 331 Software Design & Implementation

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

Final Exam CS 251, Intermediate Programming December 13, 2017

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Introduction. Introduction

Graphical User Interface (GUI)

SINGLE EVENT HANDLING

Swing from A to Z Some Simple Components. Preface

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Java Help Files. by Peter Lavin. May 22, 2004

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

GUI Event Handlers (Part I)

Part 3: Graphical User Interface (GUI) & Java Applets

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

GUI Forms and Events, Part II

CS 251 Intermediate Programming GUIs: Components and Layout

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

Original GUIs. IntroGUI 1

Programming Language Concepts: Lecture 8

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

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

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

Window Interfaces Using Swing. Chapter 12

To help you prepare for Problem 2, you are to write a simple Swing application which uses an anonymous inner class to control the application.

Agenda. Programming Seminar. By: dr. Amal Khalifa. Coordinate systems Colors Fonts Drawing shapes Graphics2D API

Introduction to the JAVA UI classes Advanced HCI IAT351

Advanced Java Unit 6: Review of Graphics and Events

User interfaces and Swing

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

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

Window Interfaces Using Swing Objects

COMPSCI 230. Software Design and Construction. Swing

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

UI Software Organization

G51PRG: Introduction to Programming Second semester Applets and graphics

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

AP CS Unit 12: Drawing and Mouse Events

Graphical User Interfaces. Comp 152

Window Interfaces Using Swing Objects

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

Graphical Applications

Java Programming Lecture 6

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

H212 Introduction to Software Systems Honors

Swing/GUI Cheat Sheet

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

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

Graphical User Interfaces 2

2IS45 Programming

CS 2113 Software Engineering

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

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

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

JAVA NOTES GRAPHICAL USER INTERFACES

Event Driven Programming

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

To gain experience using GUI components and listeners.

Class 34: Introduction to Threads

University of Cape Town Department of Computer Science. Computer Science CSC117F Solutions

ITEC 120 4/14/11. Review. Need. Objectives. GUI basics JFrame JPanel JLabel, JButton, JTextField Layout managers. Lecture 38 GUI Interactivity

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

Java IDE Programming-I

Lecture 5: Java Graphics

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Programming Languages and Techniques (CIS120)

Adding Buttons to StyleOptions.java

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

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Programming graphics

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

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

Graphical User Interface (GUI) and Object- Oriented Design (OOD)

Systems Programming Graphical User Interfaces

Transcription:

Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) How do GUIs interact with users? How do applications recognize when the user has done something? In Java this depends on 3 related concepts: events: objects that represent a user action with the system event sources: in Swing, these are components that can recognize user action, like a button or an editable text field event listeners: objects that can respond when an event occurs 2 1

Event Delegation Java runtime system generates events (AWTEvent objects) when user does something with mouse or keyboard UI components (event sources) allow you to subscribe to these events so, when an event you are interested in happens, a method in your code is called. The component delegates handling the event to the object containing the method you supply (the event listener). 3 Event Sources Event sources can generate events. The ones you will be most interested are subclases of JComponents like JButtons and JPanels You find out the kind of events they can generate by reading the Javadoc 4 2

Event Listeners An object becomes an event listener when its class implements an event listener interface. For example: public interface ActionListener extends EventListener { public void actionperformed(actionevent e); 5 the type of listener the method you must implement The event listener gets called when the event occurs if we register the event listener with the event source Events Events are instances of simple classes that supply information about what happened. For example, instances of MouseEvent have getx() and gety() methods that will tell you where the mouse event (e.g., mouse press) occurred. All event listener methods take an event as an argument. 6 3

How do I Set Up to Receive an Event? 1. Figure out what type of event you are interested in and what component it comes from. 2. Decide which object is going to handle (act on) the event. 3. Determine the correct listener interface for the type of event you are interested in. 4. Write the appropriate listener method(s) for the class of the handler object. 5. Use an addeventtypelistener() method to register the listener with the event source 7 import javax.swing.*; import java.awt.event.*; import java.awt.font; 8 The Hello Application, 1 public class Hello extends JFrame implements ActionListener 2,3 { 1 private JButton button; private int state = 0; public static void main (String args[]) { Hello hello = new Hello(); hello.setvisible( true ); 1. Figure out what type of event you are interested in and what component it comes from. 2. Decide which object is going to handle (act on) the event. 3. Determine the correct listener interface for the type of event you are interested in. 4

9 The Hello Application, 2 2 public Hello() { setdefaultcloseoperation( EXIT_ON_CLOSE ); button = new JButton( "Hello" ); button.setfont( new Font( "SansSerif", Font.BOLD, 24 ) ); button.addactionlistener( this ); 5 getcontentpane().add( button, "Center" ); setsize( 200, 200 ); 2. Decide which object is going to handle (act on) the event. 5. Use an addeventtypelistener() method to register the listener with the event source The Hello Application, 3 public void actionperformed( ActionEvent e ) { 4 if ( state == 0 ) { button.settext( "Goodbye" ); state++; else { System.exit( 0 ); 4. Write the appropriate listener method(s) for the class of the handler object. 10 5

Hello Application Framework contains Hello extends JFrame implements ActionListener registers implements JButton button event source public void actionperformed( ) event listener 11 notifies on ButtonPress Events Event Listeners You may select any object, as long as it implements ActionListener, to be the event listener. Either: Add actionperformed method to GUI element class Create new class as listener Create inner class as listener (covered later) Next example, ComboBox, has multiple event sources (3) and we must listen and distinguish the 3 types of event Example displays fonts selected by user Font family, font style, font size are chosen 12 6

ComboBoxApp public class ComboBoxApp extends JFrame { public ComboBoxApp() { settitle("combobox Example"); setdefaultcloseoperation(exit_on_close); setsize(xsize, YSIZE); ComboPanel panel= new ComboPanel(); Container contentpane= getcontentpane(); contentpane.add(panel, "Center" ); public static final int XSIZE= 600; public static final int YSIZE= 400; 13 ComboBoxApp, 2 class ComboPanel extends JPanel implements ActionListener { public ComboPanel() { String[][] fontoptions= { {"Monospaced", "Serif", "SansSerif", {"PLAIN", "BOLD", "ITALIC", {"10", "12", "14", "18", "24", "36" ; setlayout( new BorderLayout() ); chfamily= new JComboBox(fontOptions[0]); chstyle= new JComboBox(fontOptions[1]); chsize= new JComboBox(fontOptions[2]); showfont= new JLabel(); showfont.sethorizontalalignment( SwingConstants.CENTER ); showfont.setfont(new Font(curFamily, styleindex(curstyle), cursize)); showfont.settext(curfamily+" "+curstyle+" "+cursize); 14 7

ComboBoxApp, 3 JPanel combopanel = new JPanel(); combopanel.add(chfamily); combopanel.add(chstyle); combopanel.add(chsize); add( combopanel, "North" ); add( showfont, "Center" ); chfamily.addactionlistener(this); chstyle.addactionlistener(this); chsize.addactionlistener(this); private String curfamily= "Monospaced"; private String curstyle= "PLAIN"; private int cursize= 10; private JLabel showfont; private JComboBox chfamily; private JComboBox chstyle; private JComboBox chsize; 15 ComboBoxApp, 4 public void actionperformed(actionevent e) { if (e.getsource() == chfamily) curfamily= (String) chfamily.getselecteditem(); else if (e.getsource() == chstyle) curstyle= (String) chstyle.getselecteditem(); else if (e.getsource() == chsize) cursize= Integer.parseInt( (String)chSize.getSelectedItem()); showfont.setfont( new Font( curfamily, styleindex(curstyle), cursize) ); showfont.settext(curfamily +" "+ curstyle +" "+ cursize); public int styleindex(string s) { if (s.equals("bold")) return Font.BOLD; else if (s.equals("italic")) return Font.ITALIC; else return Font.PLAIN; 16 8

Event Types Semantic events vs low-level events Semantic events are generally meaningful, often the result of a sequence of low-level events. Examples: ActionEvent: user action on object (button click) AdjustmentEvent: value adjusted (scroll bar) ItemEvent: selectable item changed (combo box) TextEvent: value of text changed Low level events announce a direct manipulation of the user input devices, e.g. mouse, keyboard. Examples: MouseEvent: mouse entered, exited, pressed, released, clicked MouseMotionEvent: mouse moved, dragged 17 Mousing Example 1. Download JavaFiles.zip from the Lecture 16 materials. Unzip it into a directory and create an Eclipse project called Lecture16 located in the new directory. 2. Mousing is a very simple program that creates a button that listens for both the high level ActionEvent and low level mouse events. It prints them all out. Read the code over so you see how it is put together. 18 9

Mousing Example, 2 3. You might wonder how to find out what events a component can produce. Look at the Javadoc for JButton and search for addeventtypelistener methods. When you find one (and check base classes also), follow the hyperlink to the event listener interface. That will list a set of event types and callbacks that the component can generate. Once you have found all the add...listener methods, you will have found all the events. 4. Compile and run Mousing. Experiment with your mouse to determine under exactly what conditions a button will send an ActionEvent. For instance, do you get an ActionEvent as soon as you press the mouse over a button? What does listening for ActionEvents gain you over listening for the raw mouse events. 19 Anonymous Inner Classes Java offers a shortcut to class creation that makes writing event listeners easier. We will look at this feature more thoroughly in Lecture 25. The ComboBoxApp listens to 3 JComboBoxes and tests ActionEvents to determine their source. Wouldn't it be easier if there was an economical way to write a separate action listener for each one? 20 10

AnonComboBoxApp class AnonComboPanel extends JPanel //implements ActionListener {... //chfamily.addactionlistener(this); chfamily.addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { curfamily= (String) chfamily.getselecteditem(); showfont.setfont( new Font( curfamily, styleindex(curstyle), cursize) ); showfont.settext(curfamily + " " + curstyle + " " + cursize); ); //chstyle/chsize.addactionlistener(this); //no joint actionperformed() method 21 AnonComboBoxApp, 2 AnonComboBox no longer implements ActionListener or possesses an actionperformed method. The 3 anonymous inner classes take over that function. It looks as if we are newing an interface, which would be illegal. Actually we are creating an nameless class that will only have a single instance, the one we create right here for the addactionlistener() method. The new constructor call can NOT have arguments. chfamily.addactionlistener( new ActionListener() {... ); It can access static and instance members from the enclosing class, even private ones. 22 11

Clock Example A. Clock.java and ClockTest.java are in JavaFiles.zip. Extract them if you haven t already and add them to the new project Lecture16. B. The Clock class defines (not surprisingly) a clock object. Take a quick look at it but don t spend too much time trying to understand the details. Here is a summary of the methods: Clock(): this is the constructor. All you need to know is that it constructs the GUI (you don t have to worry about the details for now): It instantiates two buttons: Tick, Reset. It instantiates two Labels (initialized to 12 and 00 ) to numerically display the time. It adds the buttons and labels to the panel. 23 C. (Cont d) Clock Example paintcomponent(graphics g): this method draws the clock and the hours and minutes hands according to the minutes value (Once again, don t worry about the details of how this is done. We'll explore this kind of drawing in the next class.) tick(): this method increments minutes by one then repaints the clock repaint() will call the paintcomponent() method which will redraw the clock with the clock hands adjusted to the new minutes value) reset(): This method resets minutes to zero then repaints the clock. getminutes(): Access method that returns minutes. 24 12

Clock Example C. (cont d) To sum up all you need to know about this class (and this is the beauty of OOP) is the behavior dictated by its public methods, that is tick(), getminutes() and reset(), without having to worry about how the clock will draw itself. D. TestClock Class: extends JFrame. The main method creates an instance of the TestClock which will launch the constructor and will create and add a clock. E. Compile and run your project. You can see the GUI, but so far the program doesn t do anything. In this exercise, we re going to construct the GUI event model for this clock. 25 Making the Clock Tick A. We need to make the clock tick whenever the user pushes the Tick button. Make the necessary changes so that Clock implements the ActionListener interface (see the Hello or ComboBoxPanel example). Leave the actionperformed method empty for the moment. Build your project to make sure you didn t forget anything. B. Subscribe the ActionListener object (Clock) to tickbutton ( a good place to do this is at the end of the Clock constructor). C. Now write the contents of the actionperformed method to make the clock hands tick (this should take one line of code). Compile and run. Try the Tick button. You should see the clock hands moving. The labels shouldn t do anything yet. 26 13

Reset the Clock A. Now we need the clock to be reset to 12:00 whenever we push the reset button. Subscribe the ActionListener object to the resetbutton. B. Modify the actionperformed(actionevent e) method so that it can distinguish between events coming from the resetbutton and events coming from the tickbutton (see ComboBoxApp example). C. Make the clock hands reset to 12:00. Compile and run. 27 Use Anonymous Inner Classes Now rewrite the event handling to use two anonymous inner classes instead of the single actionperformed() method. (See the AnonComboBox example). Compile and test. 28 14

Displaying the Time (Extra Credit) A. We want to display the current time in the the hourlabel and minutelabel. In Clock, create a method with the following signature: public void setlabels() This method should calculate two variables: number of integer hours contained in minutes. number of minutes after removing the number of hours. Display those two variables in hourlabel and minutelabel. In order to display a string in a Label, you should make use of settext(string) (e.g. hourlabel.settext(string); Hints: 1. Integer.toString(int) takes an integer as an argument and returns a String. 2. If minutes < 60, then the hour label should show 12. 3. The minute label should always show two digits (e.g. 12:08) B. Call this method from the appropriate location. Compile and run. 29 15