MIT AITI Swing Event Model Lecture 17

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

Class 16: The Swing Event Model

Introduction. Introduction

AP CS Unit 11: Graphics and Events

SINGLE EVENT HANDLING

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

Programming Language Concepts: Lecture 8

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

First Name: AITI 2004: Exam 2 July 19, 2004

Original GUIs. IntroGUI 1

Solution register itself

RAIK 183H Examination 2 Solution. November 11, 2013

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

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

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

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

CS 251 Intermediate Programming GUIs: Event Listeners

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

Swing from A to Z Some Simple Components. Preface

COMPSCI 230. Software Design and Construction. Swing

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

Agenda. Container and Component

Swing - JButton. Adding buttons to the main window

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

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

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

Graphical User Interfaces. Comp 152

Graphical User Interfaces

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

RAIK 183H Examination 2 Solution. November 10, 2014

Programming Languages and Techniques (CIS120e)

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

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

GUI Forms and Events, Part II

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

CS 106A, Lecture 23 Interactors and GCanvas

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

Swing - JTextField. Adding a text field to the main window (with tooltips and all)

PIC 20A GUI with swing

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

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

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

First Name: AITI 2004: Exam 2 July 19, 2004

Event Driven Programming

JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup();

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

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

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Window Interfaces Using Swing Objects

Packages: Putting Classes Together

CS Exam 1 Review Suggestions

Queen s University Faculty of Arts and Science School of Computing CISC 124 Final Examination December 2004 Instructor: M. Lamb

H212 Introduction to Software Systems Honors

Graphical Interfaces

Window Interfaces Using Swing Objects

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

University of Cape Town Department of Computer Science Computer Science CSC1017F

Midterm assessment - MAKEUP Fall 2010

SE1021 Exam 2. When returning your exam, place your note-sheet on top. Page 1: This cover. Page 2 (Multiple choice): 10pts

Graphical Interfaces

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

This exam is closed textbook(s) and closed notes. Use of any electronic device (e.g., for computing and/or communicating) is NOT permitted.

7. Program Frameworks

Midterm Test II Object Oriented Programming in Java Computer Science, University of Windsor Fall 2014 Time 2 hours. Answer all questions

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

Systems Programming Graphical User Interfaces

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

CSC 1214: Object-Oriented Programming

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

1.00/1.001 Introduction to Computers and Engineering Problem Solving Final Examination - December 15, 2003

Advanced Java Unit 6: Review of Graphics and Events

Swing - JLabel. Adding a text (and HTML) labels to a GUI

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!

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

Abstract, Interface, GUIs. Ch. 11 & 16

CMP 326 Midterm Fall 2015

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

Introduction to the JAVA UI classes Advanced HCI IAT351

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

Lecture 5: Java Graphics

Java Event Handling -- 1

1005ICT Object Oriented Programming Lecture Notes

SampleApp.java. Page 1

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

CS 106A, Lecture 24 Interactors and NameSurfer

CS 180 Fall 2006 Exam II

Building Graphical User Interfaces. GUI Principles

An array is a type of variable that is able to hold more than one piece of information under a single variable name.

Java. GUI building with the AWT

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

Part I: Learn Common Graphics Components

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

CS Exam 3 - Spring 2010

Graphical User Interface

Example 3-1. Password Validation

CS Exam 3 - Spring 2010

Transcription:

MIT AITI 2004 Swing Event Model Lecture 17

The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the user. But how do GUIs interact with users? How do applications recognize when the user has done something?

package swinglab; ClickReporter import java.awt.*; import javax.swing.*; public class ClickReporter extends JFrame { public ClickReporter() { JButton mybutton = new JButton("Click here"); Container cp = getcontentpane(); cp.add(mybutton); settitle("click Printer"); setdefaultcloseoperation(exit_on_close); pack(); show(); public static void main(string[] args) { ClickReporter cr = new ClickReporter();

ClickPrinter Listener package swinglab; import java.awt.event.*; class ClickPrinter implements ActionListener { public void actionperformed(actionevent e) { System.out.println("Button was pressed");

Adding a Listener public ClickReporter() { JButton mybutton = new JButton("Click here"); ClickPrinter printer = new ClickPrinter(); click.addactionlistener(printer); Container cp = getcontentpane(); cp.add(mybutton); settitle("click Printer"); setdefaultcloseoperation(exit_on_close); pack(); show();

ClickReporter Each time you click the button a message is displayed in a console window. Click here Button was pressed

Event Handling Diagram e.g. button, menu, text fields

Event Handling To be able to handle events in Java we need 3 things: event sources event objects event listeners

Event Sources Event sources are components that can recognize user action: menus, buttons, text fields etc. Event sources have methods to add event listeners to them like addactionlistener Event source reports on events and notifies all its listeners

Event Source In our ClickReporter class we create an event source, a JButton called mybutton: JButton mybutton = new JButton("Click here"); Click here

Event Objects Objects that represent a user action (e.g. mouse click) contain detailed information about the event. When an event happens an event source sends an event object to its event listeners EventObject is the superclass ActionEvent, MouseEvent, etc. are the subclasses that we use

Event Objects In our example, the event source JButton mybutton generates an event object representing a mouse click. We are not going into details of EventObjects we will need them only as arguments to the method actionperformed in event listeners.

Event Listeners Event listeners are objects that respond when an event occurs Any object, whose class implements the ActionListener interface, can be an event listener. If the event listener has been added to an event source, the listener will be called when an event occurs on that source.

ActionListener interface Look it up at the API in the package java.awt.event: public interface ActionListener extends EventListener { public void actionperformed(actionevent e);

Event Listener In ClickReporter class we have an event listener ClickPrinter object called printer: ClickPrinter printer = new ClickPrinter(); and add this listener to our JButton click: click.addactionlistener(printer);

create an event source: JButton mybutton = new JButton("Click here"); create an event listener: ClickPrinter printer = new ClickPrinter(); add listener to the source: click.addactionlistener(printer);

Add the following data fields to your ClickReporter class: private JLabel counterlabel; private int counter = 0; Add the following three lines to the ClickReporter constructor: cp.setlayout(new FlowLayout()); ClickCounter cc = new ClickCounter(this); click.addactionlistener(cc);

Add these lines to your constructor: counterlabel = new JLabel( "The number of clicks is 0"); cp.add(counterlabel); Add this method to ClickReporter: void incrementcounter(){ counterlabel.settext( "The number of clicks is " + (++counter)); pack();

In your swinglab package create ClickCounter: package swinglab; import java.awt.event.*; class ClickCounter implements ActionListener { private ClickReporter clickreporter; ClickCounter(ClickReporter c) { clickreporter = c; public void actionperformed(actionevent e){ clickreporter.incrementcounter();

ClickCounter Diagram Button is pressed and notifies ClickCounter JButton actionperformed ClickCounter tells ClickReporter to increment its counter ClickCounter incrementcounter ClickReporter

A Calculator Listener package swinglab; import java.awt.event.*; class CalcListener implements ActionListener { private Calc calculator; CalcListener(Calc c) { calculator = c; public void actionperformed(actionevent e) { calculator.calculatepressed();

Add this method to Calc class: void calculatepressed() { double n1 = Double.parseDouble(num1.getText()); double n2 = Double.parseDouble(num2.getText()); String op = (String)operation.getSelectedItem(); double ans; if (op.equals(calc.add_op)) ans = n1 + n2; else if (op.equals(calc.sub_op)) ans = n1 - n2; else if (op.equals(calc.mul_op)) ans = n1 * n2; else ans = n1 / n2; answerlabel.settext("answer: " + ans); pack();

Add the Calc Listener In the Calc constructor, add an instance of CalcListener as a listener to the calculate button CalcListener cl = new CalcListener(this); calculate.addactionlistener(cl);

Quiz Question 1 Q: It's annoying to make a separate class for each listener. If any class can implement an interface, can't Calc implement ActionListener and listen for the events itself? A: Yes

Quiz Question 2 Q: Is it a good idea to have Calc be a listener for itself? A: No. Calc is public, and if Calc implements ActionListener, then any outside class can use Calc to listen for unrelated events. Calc is only designed to handle Calc 's own events.

Uh oh... What happens when you type letters into the textfields and click the calculate button? Exceptions are thrown!

Exception Handling Catch those exceptions and display an error message window describing the error to the user. To show the error message window use the method JOptionPane.showMessageDialog Hint: the parentcomponent should be the Calc object itself

Solution void calculatepressed() { double n1 = 0, n2 = 0; try { n1 = Double.parseDouble(num1.getText()); n2 = Double.parseDouble(num2.getText()); catch(numberformatexception e) { JOptionPane.showMessageDialog(this, "Must type two numbers, dummy!", "Not Numbers!", JOptionPane.ERROR_MESSAGE); String op = (String)operation.getSelectedItem(); double ans; if (op.equals(calc.add_op)) ans = n1 + n2; else if (op.equals(calc.sub_op)) ans = n1 - n2; else if (op.equals(calc.mul_op)) ans = n1 * n2; else ans = n1 / n2; answerlabel.settext("answer: " + ans);