Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.

Slides:



Advertisements
Similar presentations
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Advertisements

Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.
Interfaces and polymorphism Chapter 9. Interfaces  Used to express operations common to more than one purpose.  Example: You want to find the maximum.
Interfaces and Polymorphism Lesson - 8. Objectives Interfaces Supertype and subtype references Polymorphism Inner classes.
Chapter 9 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Interfaces and Polymorphism.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Graphical User Interfaces Lecture 25, Thu Apr
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling Events and Listeners Timers and Animation.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Chapter 9  Interfaces and Polymorphism 1 Chapter 9 Interfaces and Polymorphism.
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
GUIs Mimi Opkins CECS277.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 9 - Inheritance.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
Interfaces and Polymorphism 9.1 Using Interfaces for Code Reuse Defining an Interface implementing an interface 9.2 Converting between Class.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. In order to display a drawing in a frame, define a class that extends.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
Copyright © 2013 by John Wiley & Sons. All rights reserved. GRAPHICAL USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine and Ten Graphics.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Interfaces.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
For (int i = 1; i
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Graphical User Interfaces Lecture 24, Tue Apr
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Fall 2006Adapted from Java Concepts Companion Slides1 Interfaces and Polymorphism Advanced Programming ICOM 4015 Lecture 10 Reading: Java Concepts Chapter.
CHAPTER 9 INTERFACES AND POLYMORPHISM Chapter Goals: –To learn about interfaces –To be able to convert between supertype and subtype references –To understand.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
ICOM 4015 Fall 2008 Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. ICOM 4015: Advanced Programming Lecture 9 Chapter.
CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Chapter 4 Interface Types and Polymorphism: Graphics, Timer, Animation.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
Chapter 9 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Event Handling and GUI Components.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
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.
Chapter 3 Implementing Classes
Chapter 4 Interface Types and Polymorphism Part 2.
Big Java Chapters 9-10.
Lecture 3 John Woodward.
Chapter Goals To be able to declare and use interface types
Chapter 4 Interface Types and Polymorphism Part 2
Chapter 10 – Interfaces.
Chapter Three - Implementing Classes
Chapter 10 – Inheritance Big Java by Cay Horstmann
Chapter 12 Event Handling
Chapter 11 Interfaces and Polymorphism
Presentation transcript:

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces

Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To be able to declare and use interface types  To appreciate how interfaces can be used to decouple classes  To learn how to implement helper classes as inner classes  To implement event listeners in graphical applications

Copyright © 2014 by John Wiley & Sons. All rights reserved.3 Using Interfaces for Algorithm Reuse  Interface types are used to express common operations.  Interfaces make it possible to make a service available to a wide set.  This restaurant is willing to serve anyone who conforms to the Customer interface with eat and pay methods.

Copyright © 2014 by John Wiley & Sons. All rights reserved.4 Defining an Interface Type  Example: a method to compute the average of an array of Objects The algorithm for computing the average is the same in all cases Details of measurement differ  Goal: write one method that provides this service.  We can't call getBalance in one case and getArea in another.  Solution: all object who want this service must agree on a getMeasure method BankAccount's getMeasure will return the balance Country's getMeasure will return the area  Now we implement a single average method that computes the sum: sum = sum + obj.getMeasure();

Copyright © 2014 by John Wiley & Sons. All rights reserved.5 Defining an Interface Type  Problem: we need to declare a type for obj  Need to invent a new type that describes any class whose objects can be measured.  An interface type is used to specify required operations (like getMeasure): public interface Measurable { double getMeasure(); }  A Java interface type declares methods but does not provide their implementations.

Copyright © 2014 by John Wiley & Sons. All rights reserved.6 Syntax 10.1 Declaring an Interface

Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Defining an Interface Type  An interface type is similar to a class.  Differences between classes and interfaces: An interface type does not have instance variables. All methods in an interface type are abstract o They have a name, parameters, and a return type, but no implementation. All methods in an interface type are automatically public. An interface type has no constructor. o You cannot construct objects of an interface type.

Copyright © 2014 by John Wiley & Sons. All rights reserved.8 Defining an Interface Type  Implementing a reusable average method: public static double average(Measurable[] objects) { double sum = 0; for (Measurable obj : objects) { sum = sum + obj.getMeasure(); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } }  This method is can be used for objects of any class that conforms to the Measurable type.

Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Implementing an Interface Type  Use implements reserved word to indicate that a class implements an interface type: public class BankAccount implements Measurable { … public double getMeasure() { return balance; } }  BankAccount objects are instances of the Measurable type: Measurable obj = new BankAccount(); // OK

Copyright © 2014 by John Wiley & Sons. All rights reserved.10 Implementing an Interface Type  A variable of type Measurable holds a reference to an object of some class that implements the Measurable interface.  Country class can also implement the Measurable interface: public class Country implements Measurable { public double getMeasure() { return area; }... }  Use interface types to make code more reusable.

Copyright © 2014 by John Wiley & Sons. All rights reserved.11 Implementing an Interface Type  Put the average method in a class - say Data Figure 1 UML Diagram of the Data Class and the Classes that Implement the Measurable Interface  Data class is decoupled from the BankAccount and Country classes.

Copyright © 2014 by John Wiley & Sons. All rights reserved.12 Syntax 10.2 Implementing an Interface

Copyright © 2014 by John Wiley & Sons. All rights reserved.13 section_1/Data.javaData.java 1 public class Data 2 { 3 /** 4 Computes the average of the measures of the given objects. objects an array of Measurable objects the average of the measures 7 */ 8 public static double average(Measurable[] objects) 9 { 10 double sum = 0; 11 for (Measurable obj : objects) 12 { 13 sum = sum + obj.getMeasure(); 14 } 15 if (objects.length > 0) { return sum / objects.length; } 16 else { return 0; } 17 } 18 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.14 section_1/MeasurableTester.javaMeasurableTester.java 1 /** 2 This program demonstrates the measurable BankAccount and Country classes. 3 */ 4 public class MeasurableTester 5 { 6 public static void main(String[] args) 7 { 8 Measurable[] accounts = new Measurable[3]; 9 accounts[0] = new BankAccount(0); 10 accounts[1] = new BankAccount(10000); 11 accounts[2] = new BankAccount(2000); double averageBalance = Data.average(accounts); 14 System.out.println("Average balance: " + averageBalance); 15 System.out.println("Expected: 4000"); Measurable[] countries = new Measurable[3]; 18 countries[0] = new Country("Uruguay", ); 19 countries[1] = new Country("Thailand", ); 20 countries[2] = new Country("Belgium", 30510); double averageArea = Data.average(countries); 23 System.out.println("Average area: " + averageArea); 24 System.out.println("Expected: "); 25 } 26 } Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.15 section_1/MeasurableTester.javaMeasurableTester.java Program Run: Average balance: 4000 Expected: 4000 Average area: Expected:

Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Comparing Interfaces and Inheritance  Here is a different interface: Named public interface Named { String getName(); }  A class can implement more than one interface: public class Country implements Measurable, Named  A class can only extend (inherit from) a single superclass.  An interface specifies the behavior that an implementing class should supply - no implementation.  A superclass provides some implementation that a subclass inherits.  Develop interfaces when you have code that processes objects of different classes in a common way.

Copyright © 2014 by John Wiley & Sons. All rights reserved.17 Converting From Classes to Interfaces  You can convert from a class type to an interface type, provided the class implements the interface.  A Measurable variable can refer to an object of the BankAccount class because BankAccount implements the Measurable interface: BankAccount account = new BankAccount(1000); Measurable meas = account; // OK  A Measurable variable can refer to an object of the Country class because that class also implements the Measurable interface: Country uruguay = new Country("Uruguay", ); Measurable meas = uruguay; // Also OK // Also OK

Copyright © 2014 by John Wiley & Sons. All rights reserved.18 Converting From Classes to Interfaces  A Measurable variable cannot refer to an object of the Rectangle class because Rectangle doesn't implement Measurable: Measurable meas = new Rectangle(5, 10, 20, 30); // ERROR

Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Variables of Class and Interface Types Figure 2 Two references to the same object

Copyright © 2014 by John Wiley & Sons. All rights reserved.20 Variables of Class and Interface Types Figure 3 An Interface Reference Can Refer to an Object of Any Class that Implements the Interface  Method calls on an interface reference are polymorphic. The appropriate method is determined at run time.

Copyright © 2014 by John Wiley & Sons. All rights reserved.21 Casting from Interfaces to Classes  Method to return the object with the largest measure: public static Measurable larger(Measurable obj1, Measurable obj) { if (obj1.getMeasure() > obj2.getMeasure()) { return obj1; } else { return obj2; } }  Returns the object with the larger measure, as a Measurable reference. Country uruguay = new Country("Uruguay", ); Country thailand = new Country("Thailand", ); Measurable max = larger(uruguay, thailand);

Copyright © 2014 by John Wiley & Sons. All rights reserved.22 Casting from Interfaces to Classes  You know that max refers to a Country object, but the compiler does not.  Solution: cast Country maxCountry = (Country) max; String name = maxCountry.getName();  You need a cast to convert from an interface type to a class type.  If you are wrong and max doesn't refer to a Country object, the program throws an exception at runtime.  If a Person object is actually a Superhero, you need a cast before you can apply any Superhero methods.

Copyright © 2014 by John Wiley & Sons. All rights reserved.23 The Comparable Interface  Comparable interface is in the standard Java library.  Comparable interface has a single method: public interface Comparable { int compareTo(Object otherObject); }  The call to the method: a.compareTo(b)  The compareTo method returns: a negative number if a should come before b, zero if a and b are the same a positive number if b should come before a.  Implement the Comparable interface so that objects of your class can be compared, for example, in a sort method.

Copyright © 2014 by John Wiley & Sons. All rights reserved.24 The Comparable Interface  BankAccount class' implementation of Comparable: public class BankAccount implements Comparable {... public int compareTo(Object otherObject) { BankAccount other = (BankAccount) otherObject; if (balance < other.balance) { return -1; } if (balance > other.balance) { return 1; } return 0; }... }  compareTo method has a parameter of reference type Object  To get a BankAccount reference: BankAccount other = (BankAccount) otherObject;

Copyright © 2014 by John Wiley & Sons. All rights reserved.25 The Comparable Interface  Because the BankAccount class implements the Comparable interface, you can sort an array of bank accounts with the Arrays.sort method: BankAccount[] accounts = new BankAccount[3]; accounts[0] = new BankAccount(10000); accounts[1] = new BankAccount(0); accounts[2] = new BankAccount(2000); Arrays.sort(accounts);  Now the accounts array is sorted by increasing balance.  The compareTo method checks whether another object is larger or smaller.

Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Using Interfaces for Callbacks  Limitations of Measurable interface: Can add Measurable interface only to classes under your control Can measure an object in only one way o E.g., cannot analyze a set of cars by both speed and price  Callback: a mechanism for specifying code that is executed at a later time.  Problem: the responsibility of measuring lies with the added objects themselves.  Alternative: give the average method both the data to be averaged and a method of measuring.

Copyright © 2014 by John Wiley & Sons. All rights reserved.27 Using Interfaces for Callbacks  Create an interface: public interface Measurer { double measure(Object anObject); }  All objects can be converted to Object.

Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Using Interfaces for Callbacks  The code that makes the call to the callback receives an object of class that implements this interface: public static double average(Object[] objects, Measurer meas) { double sum = 0; for (Object obj : objects) { sum = sum + meas.measure(obj); } if (objects.length > 0) { return sum / objects.length; } else { return 0; } }  The average method simply makes a callback to the measure method whenever it needs to measure any object.

Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Using Interfaces for Callbacks  A specific callback is obtained by implementing the Measurer interface: public class AreaMeasurer implements Measurer { public double measure(Object anObject) { Rectangle aRectangle = (Rectangle) anObject; double area = aRectangle.getWidth() * aRectangle.getHeight(); return area; } }  Must cast from Object to Rectangle: Rectangle aRectangle = (Rectangle) anObject;

Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Using Interfaces for Callbacks  To compute the average area of rectangles: construct an object of the AreaMeasurer class and pass it to the average method: Measurer areaMeas = new AreaMeasurer(); Rectangle[] rects = { new Rectangle(5, 10, 20, 30), new Rectangle(10, 20, 30, 40) }; double averageArea = average(rects, areaMeas);  The average method will ask the AreaMeasurer object to measure the rectangles.

Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Using Interfaces for Callbacks  The Data class (which holds the average method) is decoupled from the class whose objects it processes (Rectangle).  You provide a small “helper” class AreaMeasurer, to process rectangles. Figure 6 UML Diagram of the Data Class and the Measurer Interface

Copyright © 2014 by John Wiley & Sons. All rights reserved.32 section_4/Measurer.javaMeasurer.java 1 /** 2 Describes any class whose objects can measure other objects. 3 */ 4 public interface Measurer 5 { 6 /** 7 Computes the measure of an object. anObject the object to be measured the measure 10 */ 11 double measure(Object anObject); 12 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.33 section_4/AreaMeasurer.javaAreaMeasurer.java 1 import java.awt.Rectangle; 2 3 /** 4 Objects of this class measure rectangles by area. 5 */ 6 public class AreaMeasurer implements Measurer 7 { 8 public double measure(Object anObject) 9 { 10 Rectangle aRectangle = (Rectangle) anObject; 11 double area = aRectangle.getWidth() * aRectangle.getHeight(); 12 return area; 13 } 14 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.34 section_4/Data.javaData.java 1 public class Data 2 { 3 /** 4 Computes the average of the measures of the given objects. objects an array of objects meas the measurer for the objects the average of the measures 8 */ 9 public static double average(Object[] objects, Measurer meas) 10 { 11 double sum = 0; 12 for (Object obj : objects) 13 { 14 sum = sum + meas.measure(obj); 15 } 16 if (objects.length > 0) { return sum / objects.length; } 17 else { return 0; } 18 } 19 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.35 section_4/MeasurerTester.javaMeasurerTester.java 1 import java.awt.Rectangle; 2 3 /** 4 This program demonstrates the use of a Measurer. 5 */ 6 public class MeasurerTester 7 { 8 public static void main(String[] args) 9 { 10 Measurer areaMeas = new AreaMeasurer(); Rectangle[] rects = new Rectangle[] 13 { 14 new Rectangle(5, 10, 20, 30), 15 new Rectangle(10, 20, 30, 40), 16 new Rectangle(20, 30, 5, 15) 17 }; double averageArea = Data.average(rects, areaMeas); 20 System.out.println("Average area: " + averageArea); 21 System.out.println("Expected: 625"); 22 } 23 } Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.36 section_4/MeasurerTester.javaMeasurerTester.java Program Run: Average area: 625 Expected: 625

Copyright © 2014 by John Wiley & Sons. All rights reserved.37 Inner Classes  Trivial class can be declared inside a method: public class MeasurerTester { public static void main(String[] args) { class AreaMeasurer implements Measurer {... } Measurer areaMeas = new AreaMeasurer(); double averageArea = Data.average(rects, areaMeas);... } }

Copyright © 2014 by John Wiley & Sons. All rights reserved.38 Inner Classes  An inner class is a class that is declared inside another class.

Copyright © 2014 by John Wiley & Sons. All rights reserved.39 Inner Classes  You can declare inner class inside an enclosing class, but outside its methods.  It is available to all methods of enclosing class: public class MeasurerTester { class AreaMeasurer implements Measurer {... } public static void main(String[] args) { Measurer areaMeas = new AreaMeasurer(); double averageArea = Data.average(rects, areaMeas);... } }

Copyright © 2014 by John Wiley & Sons. All rights reserved.40 Inner Classes  Compiler turns an inner class into a regular class file with a strange name: MeasurerTester$1AreaMeasurer.class  Inner classes are commonly used for utility classes that should not be visible elsewhere in a program.

Copyright © 2014 by John Wiley & Sons. All rights reserved.41 Event Handling  In an event-driven user interface, the program receives an event whenever the user manipulates an input component.  User interface events include key presses, mouse moves, button clicks, and so on.  Most programs don't want to be flooded by irrelevant events.  A program must indicate which events it needs to receive.

Copyright © 2014 by John Wiley & Sons. All rights reserved.42 Event Handling  Event listeners: A program indicates which events it needs to receive by installing event listener objects Belongs to a class provided by the application programmer Its methods describe the actions to be taken when an event occurs Notified when event happens  Event source: User interface component that generates a particular event Add an event listener object to the appropriate event source When an event occurs, the event source notifies all event listeners

Copyright © 2014 by John Wiley & Sons. All rights reserved.43 Event Handling  Example: A program that prints a message whenever a button is clicked.  Button listeners must belong to a class that implements the ActionListener interface: public interface ActionListener { void actionPerformed(ActionEvent event); }  Your job is to supply a class whose actionPerformed method contains the instructions that you want executed whenever the button is clicked.

Copyright © 2014 by John Wiley & Sons. All rights reserved.44 Event Handling  Your job is to supply a class whose actionPerformed method contains the instructions that you want executed whenever the button is clicked.

Copyright © 2014 by John Wiley & Sons. All rights reserved.45 section_7_1/ClickListener.javaClickListener.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 4 /** 5 An action listener that prints a message. 6 */ 7 public class ClickListener implements ActionListener 8 { 9 public void actionPerformed(ActionEvent event) 10 { 11 System.out.println("I was clicked."); 12 } 13 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.46 Event Handling - Listening to Events  event parameter of actionPerformed contains details about the event, such as the time at which it occurred.  Construct an object of the listener and add it to the button: ActionListener listener = new ClickListener(); button.addActionListener(listener);  Whenever the button is clicked, it calls: listener.actionPerformed(event); And the message is printed.  Similar to a callback  Use a JButton component for the button; attach an ActionListener to the button.

Copyright © 2014 by John Wiley & Sons. All rights reserved.47 section_7_1/ButtonViewer.javaButtonViewer.java 1 import java.awt.event.ActionListener; 2 import javax.swing.JButton; 3 import javax.swing.JFrame; 4 5 /** 6 This program demonstrates how to install an action listener. 7 */ 8 public class ButtonViewer 9 { 10 private static final int FRAME_WIDTH = 100; 11 private static final int FRAME_HEIGHT = 60; public static void main(String[] args) 14 { 15 JFrame frame = new JFrame(); 16 JButton button = new JButton("Click me!"); 17 frame.add(button); ActionListener listener = new ClickListener(); 20 button.addActionListener(listener); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 23 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 24 frame.setVisible(true); 25 } 26 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.48 Event Handling  Whenever a button is pressed, the actionPerformed method is called on all listeners.  Specify button click actions through classes that implement the ActionListener interface.

Copyright © 2014 by John Wiley & Sons. All rights reserved.49 Using Inner Classes for Listeners  Implement simple listener classes as inner classes like this: JButton button = new JButton("..."); // This inner class is declared in the same method // as the button variable class MyListener implements ActionListener {... } ActionListener listener = new MyListener(); button.addActionListener(listener);  Advantages Places the trivial listener class exactly where it is needed, without cluttering up the remainder of the project Methods of an inner class can access instance variables and methods of the surrounding class

Copyright © 2014 by John Wiley & Sons. All rights reserved.50 Using Inner Classes for Listeners  Local variables that are accessed by an inner class method must be declared as final.  Example: add interest to a bank account whenever a button is clicked: JButton button = new JButton("Add Interest"); final BankAccount account = new BankAccount(INITIAL_BALANCE); // This inner class is declared in the same method as the account and // button variables. class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { // The listener method accesses the account variable // from the surrounding block double interest = account.getBalance() * INTEREST_RATE / 100; account.deposit(interest); } }; ActionListener listener = new AddInterestListener(); button.addActionListener(listener);

Copyright © 2014 by John Wiley & Sons. All rights reserved.51 section_7_2/InvestmentViewer1.javaInvestmentViewer1.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 6 /** 7 This program demonstrates how an action listener can access 8 a variable from a surrounding block. 9 */ 10 public class InvestmentViewer1 11 { 12 private static final int FRAME_WIDTH = 120; 13 private static final int FRAME_HEIGHT = 60; private static final double INTEREST_RATE = 10; 16 private static final double INITIAL_BALANCE = 1000; public static void main(String[] args) 19 { 20 JFrame frame = new JFrame(); // The button to trigger the calculation 23 JButton button = new JButton("Add Interest"); 24 frame.add(button); 25 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.52 section_7_2/InvestmentViewer1.javaInvestmentViewer1.java 26 // The application adds interest to this bank account 27 final BankAccount account = new BankAccount(INITIAL_BALANCE); class AddInterestListener implements ActionListener 30 { 31 public void actionPerformed(ActionEvent event) 32 { 33 // The listener method accesses the account variable 34 // from the surrounding block 35 double interest = account.getBalance() * INTEREST_RATE / 100; 36 account.deposit(interest); 37 System.out.println("balance: " + account.getBalance()); 38 } 39 } ActionListener listener = new AddInterestListener(); 42 button.addActionListener(listener); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 45 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 46 frame.setVisible(true); 47 } 48 } Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.53 section_7_2/InvestmentViewer1.javaInvestmentViewer1.java Program Run: balance: balance: balance: balance:

Copyright © 2014 by John Wiley & Sons. All rights reserved.54 Building Applications with Buttons  Example: investment viewer program; whenever button is clicked, interest is added, and new balance is displayed:  Construct an object of the JButton class: JButton button = new JButton("Add Interest");  We need a user interface component that displays a message: JLabel label = new JLabel("balance: " + account.getBalance());

Copyright © 2014 by John Wiley & Sons. All rights reserved.55 Building Applications with Buttons  Use a JPanel container to group multiple user interface components together: JPanel panel = new JPanel(); panel.add(button); panel.add(label); frame.add(panel);

Copyright © 2014 by John Wiley & Sons. All rights reserved.56 Building Applications with Buttons  Listener class adds interest and displays the new balance: class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double interest = account.getBalance() * INTEREST_RATE / 100; account.deposit(interest); label.setText("balance=” + account.getBalance()); } }  Add AddInterestListener as inner class so it can have access to surrounding final variables (account and label).

Copyright © 2014 by John Wiley & Sons. All rights reserved.57 section_8/InvestmentViewer2.javaInvestmentViewer2.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 import javax.swing.JLabel; 6 import javax.swing.JPanel; 7 8 /** 9 This program displays the growth of an investment. 10 */ 11 public class InvestmentViewer2 12 { 13 private static final int FRAME_WIDTH = 400; 14 private static final int FRAME_HEIGHT = 100; private static final double INTEREST_RATE = 10; 17 private static final double INITIAL_BALANCE = 1000; public static void main(String[] args) 20 { 21 JFrame frame = new JFrame(); // The button to trigger the calculation 24 JButton button = new JButton("Add Interest"); 25 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.58 section_8/InvestmentViewer2.javaInvestmentViewer2.java 26 // The application adds interest to this bank account 27 final BankAccount account = new BankAccount(INITIAL_BALANCE); // The label for displaying the results 30 final JLabel label = new JLabel("balance: " + account.getBalance()); // The panel that holds the user interface components 33 JPanel panel = new JPanel(); 34 panel.add(button); 35 panel.add(label); 36 frame.add(panel); class AddInterestListener implements ActionListener 39 { 40 public void actionPerformed(ActionEvent event) 41 { 42 double interest = account.getBalance() * INTEREST_RATE / 100; 43 account.deposit(interest); 44 label.setText("balance: " + account.getBalance()); 45 } 46 } ActionListener listener = new AddInterestListener(); 49 button.addActionListener(listener); 50 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.59 section_8/InvestmentViewer2.javaInvestmentViewer2.java 51 frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); 52 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 53 frame.setVisible(true); 54 } 55 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.60 Processing Timer Events  javax.swing.Timer generates equally spaced timer events, sending events to installed action listeners.  Useful whenever you want to have an object updated in regular intervals.  Declare a class that implements the ActionListener interface: class MyListener implements ActionListener { void actionPerformed(ActionEvent event) { Listener action (executed at each timer event) } }

Copyright © 2014 by John Wiley & Sons. All rights reserved.61 Processing Timer Events  To create a timer, specify the frequency of the events and an object of a class that implements the ActionListener interface: MyListener listener = new MyListener(); Timer t = new Timer(interval, listener); t.start();

Copyright © 2014 by John Wiley & Sons. All rights reserved.62 section_9/RectangleComponent.javaRectangleComponent.java 1 import java.awt.Graphics; 2 import java.awt.Graphics2D; 3 import java.awt.Rectangle; 4 import javax.swing.JComponent; 5 6 /** 7 This component displays a rectangle that can be moved. 8 */ 9 public class RectangleComponent extends JComponent 10 { 11 private static final int BOX_X = 100; 12 private static final int BOX_Y = 100; 13 private static final int BOX_WIDTH = 20; 14 private static final int BOX_HEIGHT = 30; private Rectangle box; 17 Continued Displays a rectangle that moves. The repaint method causes a component to repaint itself. Call this method whenever you modify the shapes that the paintComponent method draws.

Copyright © 2014 by John Wiley & Sons. All rights reserved.63 section_9/RectangleComponent.javaRectangleComponent.java 18 public RectangleComponent() 19 { 20 // The rectangle that the paintComponent method draws 21 box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); 22 } public void paintComponent(Graphics g) 25 { 26 Graphics2D g2 = (Graphics2D) g; 27 g2.draw(box); 28 } /** 31 Moves the rectangle by a given amount. dx the amount to move in the x-direction dy the amount to move in the y-direction 34 */ 35 public void moveRectangleBy(int dx, int dy) 36 { 37 box.translate(dx, dy); 38 repaint(); 39 } 40 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.64 section_9/RectangleFrame.javaRectangleFrame.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JFrame; 4 import javax.swing.Timer; 5 6 /** 7 This frame contains a moving rectangle. 8 */ 9 public class RectangleFrame extends JFrame 10 { 11 private static final int FRAME_WIDTH = 300; 12 private static final int FRAME_HEIGHT = 400; private RectangleComponent scene; class TimerListener implements ActionListener 17 { 18 public void actionPerformed(ActionEvent event) 19 { 20 scene.moveRectangleBy(1, 1); 21 } 22 } 23 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.65 section_9/RectangleFrame.javaRectangleFrame.java 24 public RectangleFrame() 25 { 26 scene = new RectangleComponent(); 27 add(scene); setSize(FRAME_WIDTH, FRAME_HEIGHT); ActionListener listener = new TimerListener(); final int DELAY = 100; // Milliseconds between timer ticks 34 Timer t = new Timer(DELAY, listener); 35 t.start(); 36 } 37 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.66 section_9/RectangleViewer.javaRectangleViewer.java 1 import javax.swing.JFrame; 2 3 /** 4 This program moves the rectangle. 5 */ 6 public class RectangleViewer 7 { 8 public static void main(String[] args) 9 { 10 JFrame frame = new RectangleFrame(); 11 frame.setTitle("An animated rectangle"); 12 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 13 frame.setVisible(true); 14 } 15 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.67 Mouse Events  Use a mouse listener to capture mouse events.  Implement the MouseListener interface which has five methods: public interface MouseListener { void mousePressed(MouseEvent event); // Called when a mouse button has been pressed on a component void mouseReleased(MouseEvent event); // Called when a mouse button has been released on a component void mouseClicked(MouseEvent event); // Called when the mouse has been clicked on a component void mouseEntered(MouseEvent event); // Called when the mouse enters a component void mouseExited(MouseEvent event); // Called when the mouse exits a component }

Copyright © 2014 by John Wiley & Sons. All rights reserved.68 Mouse Events  Add a mouse listener to a component by calling the addMouseListener method: public class MyMouseListener implements MouseListener { // Implements five methods } MouseListener listener = new MyMouseListener(); component.addMouseListener(listener);  Sample program: enhance RectangleComponent – when user clicks on rectangle component, move the rectangle to the mouse location.

Copyright © 2014 by John Wiley & Sons. All rights reserved.69 section_10/RectangleComponent2.javaRectangleComponent2.java 1 import java.awt.Graphics; 2 import java.awt.Graphics2D; 3 import java.awt.Rectangle; 4 import javax.swing.JComponent; 5 6 /** 7 This component displays a rectangle that can be moved. 8 */ 9 public class RectangleComponent2 extends JComponent 10 { 11 private static final int BOX_X = 100; 12 private static final int BOX_Y = 100; 13 private static final int BOX_WIDTH = 20; 14 private static final int BOX_HEIGHT = 30; private Rectangle box; public RectangleComponent2() 19 { 20 // The rectangle that the paintComponent method draws 21 box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); 22 } 23 Continued First add a moveRectangle method to RectangleComponent :

Copyright © 2014 by John Wiley & Sons. All rights reserved.70 section_10/RectangleComponent2.javaRectangleComponent2.java 24 public void paintComponent(Graphics g) 25 { 26 Graphics2D g2 = (Graphics2D) g; 27 g2.draw(box); 28 } /** 31 Moves the rectangle to the given location. x the x-position of the new location y the y-position of the new location 34 */ 35 public void moveRectangleTo(int x, int y) 36 { 37 box.setLocation(x, y); 38 repaint(); 39 } 40 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.71 Mouse Events  Call repaint to tell the component to repaint itself and show the rectangle in its new position.  When the mouse is pressed,the mouse listener moves the rectangle to the mouse location: class MousePressListener implements MouseListener { public void mousePressed(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x, y); } // Do-nothing methods public void mouseReleased(MouseEvent event) {} public void mouseClicked(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }  All five methods of the interface must be implemented; unused methods can be empty.

Copyright © 2014 by John Wiley & Sons. All rights reserved.72 RectangleViewer2 Program Run Figure 9 Clicking the Mouse Moves the Rectangle

Copyright © 2014 by John Wiley & Sons. All rights reserved.73 section_10/RectangleFrame2.javaRectangleFrame2.java 1 import java.awt.event.MouseListener; 2 import java.awt.event.MouseEvent; 3 import javax.swing.JFrame; 4 5 /** 6 This frame contains a moving rectangle. 7 */ 8 public class RectangleFrame2 extends JFrame 9 { 10 private static final int FRAME_WIDTH = 300; 11 private static final int FRAME_HEIGHT = 400; private RectangleComponent2 scene; class MousePressListener implements MouseListener 16 { 17 public void mousePressed(MouseEvent event) 18 { 19 int x = event.getX(); 20 int y = event.getY(); 21 scene.moveRectangleTo(x, y); 22 } 23 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.74 section_10/RectangleFrame2.javaRectangleFrame2.java 24 // Do-nothing methods 25 public void mouseReleased(MouseEvent event) {} 26 public void mouseClicked(MouseEvent event) {} 27 public void mouseEntered(MouseEvent event) {} 28 public void mouseExited(MouseEvent event) {} 29 } public RectangleFrame2() 32 { 33 scene = new RectangleComponent2(); 34 add(scene); MouseListener listener = new MousePressListener(); 37 scene.addMouseListener(listener); setSize(FRAME_WIDTH, FRAME_HEIGHT); 40 } 41 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.75 section_10/RectangleViewer2.javaRectangleViewer2.java 1 import javax.swing.JFrame; 2 3 /** 4 This program displays a rectangle that can be moved with the mouse. 5 */ 6 public class RectangleViewer2 7 { 8 public static void main(String[] args) 9 { 10 JFrame frame = new RectangleFrame2(); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 frame.setVisible(true); 13 } 14 }