CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 4: Interface Types.

Slides:



Advertisements
Similar presentations
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Advertisements

Applets Graphical Java programs Run inside web browser Platform-neutral Easy deployment--loads when needed Secure.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Intro to Graphics.
Chapter 3: Implementing Classes Part 1. To become familiar with the process of implementing classes To be able to implement simple methods To understand.
Carnegie Mellon University, MISM1 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Java Concepts Chapter 2 – Graphical Applications Mr. Smith AP Computer Science A.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
Design Patterns and Graphical User Interfaces Horstmann ,
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CS 151: Object-Oriented Design October 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 5 - Graphics.
Interfaces & Polymorphism part 2:
CHAPTER 2 Using Objects. Basic Programming Terminology  Computer program process values.  Numbers (digits)  Words (Strings)  These values are different.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Three: Implementing Classes.
Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)
Chapter 3 – Implementing Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 4: Applets and Graphics 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 4 Applets and Graphics.
Chapter 4 Fundamental Data Types. Chapter Goals To be able to write simple applets To display graphical shapes such as lines and ellipses To use colors.
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.
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.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
ICOM 4015: Advanced Programming Lecture 3 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Three:
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
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.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
Fall 2006Adapted from Java Concepts Companion Slides1 Programming Graphics Advanced Programming ICOM 4015 Lecture 14 Reading: Java Concepts Chapter 5.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Chapter 4 Interface Types and Polymorphism: Graphics, Timer, Animation.
CS 151: Object-Oriented Design October 1 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
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 3: Implementing Classes Part 1. To become familiar with the process of implementing classes To be able to implement simple methods To understand.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 3 – Implementing Classes.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Break Time! Graphical User Interface (GUI) NO EXAM….ONLY PROJECT!
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Chapter 4 Interface Types and Polymorphism Part 2.
Chapter 4 Interfaces and Polymorphism Object-Oriented Design & Patterns Cay S. Horstmann.
Interface types and Polymorphism
Chapter 5 Programming Graphics
Chapter Goals To become familiar with the process of implementing classes To be able to implement and test simple methods To understand the purpose and.
Chapter 3 – Implementing Classes
ITEC324 Principle of CS III
Chapter Three: Implementing Classes
Chapter 4 Interface Types and Polymorphism Part 2
Chapter 4 Interface Types and Polymorphism Part 1
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Chapter Three - Implementing Classes
Fundamental Data Types
A Quick Java Swing Tutorial
Constructors, GUI’s(Using Swing) and ActionListner
ITEC324 Principle of CS III
Chapter 4 Interface Types and Polymorphism Part 1
Presentation transcript:

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 4: Interface Types and Polymorphism CPSC 2100 Software Design and Development 1

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Chapter Topics Displaying an Image Polymorphism The Comparable Interface The Comparator Interface Anonymous Classes Frames and User Interface Components User Interface Actions Timers Drawing Shapes Designing an Interface 2

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Chapter Objective Define a set of operations (the interface) and statements that specify how to carry out the operations and how to represent object state (the implementation). Separate the interface concept from that of a class can help in the development of reusable code. Focusing on interface types first, you will study polymorphism in its purist and simplest form. 3

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Displaying an Image Use JOptionPane to display message: JOptionPane.showMessageDialog(null, "Hello, World!"); Note icon to the left 4

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Displaying an Image Can specify arbitrary image file JOptionPane.showMessageDialog( null, // parent window "Hello, World!", // message "Message", // window title JOptionPane.INFORMATION_MESSAGE, // message type new ImageIcon("globe.gif")); 5

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Displaying an Image What if we don't want to generate an image file? Fortunately, can use any class that implements Icon interface type. ImageIcon is one such class Easy to supply your own class. public interface Icon { int getIconWidth(); int getIconHeight(); voif paintIcon(Component c, Graphics g, int x, int y); } 6

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Interface Types Technical remarks: 1.No implementation. 2.All methods of an interface are automatically public. 3.Implementing class must supply implementation of all methods. showMessageDialog expects Icon object. Ok to pass MarsIcon. 7

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Icon Interface Type and Implementing Classes 8 MarsIcon.java CarIcon.java IconTester.java

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Polymorphism showMessageDialog doesn't know which icon is passed o ImageIcon? o MarsIcon? o...? Compute the size of the dialog box: width = iconWidth + message width + blank separation space The actual type of anIcon is not Icon. There are no objects of type Icon. anIcon belongs to a class that implements Icon. That class defines a getIconWidth method. 9

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Polymorphism Which getIconWidth method is called? Could be oMarsIcon.getIconWidth oImageIcon.getIconWidth o... Depends on object to which anIcon reference points, e.g. showMessageDialog(..., new MarsIcon(50)) Polymorphism: Select different methods according to actual object type. 10

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Benefits of Polymorphism The ability to select appropriate method for a particular object is called polymorphism.  Loose coupling showMessageDialog decoupled from ImageIcon. Doesn't need to know about image processing.  Extensibility Client can supply new icon types. 11

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Comparable Interface Type Collections class has static sort method: ArrayList a =... Collections.sort(a); Objects in array list must implement the Comparable interface type. public interface Comparable { int compareTo(T other); } 12

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Comparable Interface Type object1.compareTo(object2) returns o Negative number if object1 less than object2. o 0 if objects identical. o Positive number if object1 greater than object2. Why implement Comparable interface type? o sort method compares and rearranges elements if (object1.compareTo(object2) > 0)... Country class: compare countries by area Country.java CountrySortTester.java 13

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Comparator interface type How can we sort countries by name? Can't implement Comparable twice! Comparator interface type gives added flexibility. public interface Comparator { int compare(T obj1, T obj2); } Pass comparator object to sort: Collections.sort(list, comp); 14

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Comparator interface type Country.java CountryComparatorByName.java ComparatorTester.java Comparator object is a function object This particular comparator object has no state. 15

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 The Comparator interface type State can be useful, e.g. flag to sort in ascending or descending order. public class CountryComparator implements Comparator { public CountryComparator(boolean ascending) { if (ascending) direction = 1; else direction = -1; } public int compare(Country country1, Country country2) { return direction * country1.getName().compareTo(country2.getName()); } private int direction; } 16

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Anonymous Classes No need to name objects that are used only once Collections.sort(countries, new CountryComparatorByName()); No need to name classes that are used only once Comparator comp = new Comparator () { public int compare(Country country1, Country country2) { return country1.getName().compareTo(country2.getName()); } }; 17

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Anonymous Classes Commonly used in factory methods: public static Comparator comparatorByName() { return new Comparator () { public int compare(Country country1, Country country2 {... } }; } Collections.sort(a, Country.comparatorByName()); Neat arrangement if multiple comparators make sense (by name, by area,...) 18

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Frames 1. Construct an object of the JFrame class. JFrame aFrame = new JFrame(); 2. Set the size of the frame. frame.setSize(with, height); 3. Set the title of the frame. frame.setTitle(“......”); 4. Set the default close operation. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 5. Make the frame visible. frame.setVisible(true); 19 (3) Width Height

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Frames Construct components JButton helloButton = new JButton("Say Hello"); Set frame layout frame.setLayout(new FlowLayout()); Add components to frame frame.add(helloButton); FrameTester.java 20

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 User Interface Actions Previous program's buttons don't have any effect. Add listener object(s) to button. Belong to class implementing ActionListener interface type. public interface ActionListener { void actionPerformed(ActionEvent event); } Listeners are notified when button is clicked. 21

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 User Interface Actions Add action code into actionPerformed method Gloss over routine code helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } }); When button is clicked, text field is set. 22

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 User Interface Actions FrameTester.java Constructor attaches listener: helloButton.addActionListener(listener); Button remembers all listeners. When button clicked, button notifies listeners listener.actionPerformed(event); Listener sets text of text field textField.setText("Hello, World!"); 23

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Accessing Variables from Enclosing Scope Remarkable: Inner class can access variables from enclosing scope. e.g. textField Can access enclosing instance fields, local variables. Important: Local variables must be marked final. final JTextField textField =...; 24

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Timers Supply delay, action listener ActionListener listener =...; final int DELAY = 1000; // 1000 millisec = 1 sec Timer t = new Timer(DELAY, listener); t.start(); Action listener called when delay elapsed. FrameTester.java 25

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Shapes paintIcon method receives graphics context of type Graphics. Actually a Graphics2D object in modern Java versions public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D)g;... } Can draw any object that implements Shape interface Shape s =...; g2.draw(s); 26

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Rectangles and Ellipses Rectangle2D.Double constructed with o top left corner o width o height g2.draw(new Rectangle2D.Double(x, y, width, height)); For Ellipse2D.Double, specify bounding box. 27

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Ellipses 28

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Line Segments Point2D.Double is a point in the plane Line2D.Double joins to points Point2D.Double start = new Point2D.Double(x1, y1); Point2D.Double end = new Point2D.Double(x2, y2); Shape segment = new Line2D.Double(start, end); g2.draw(segment); 29

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Relationship Between Shape Classes 30

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Text g2.drawString(text, x, y); x, y are base point coordinates 31

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Cars Draw two cars: one in top-left corner of window, and another in the bottom right Compute bottom right position, inside paintComponent method: int x = getWidth() - 60; int y = getHeight() - 30; Car car2 = new Car(x, y); getWidth and getHeight are applied to object that executes paintComponent If window is resized paintComponent is called and car position recomputed.

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Drawing Cars (cont.) Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Plan Complex Shapes on Graph Paper Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Classes of Car Drawing Program Car: responsible for drawing a single car Two objects of this class are constructed, one for each car CarComponent: displays the drawing CarViewer: shows a frame that contains a CarComponent

CPSC 2100 University of Tennessee at Chattanooga – Fall import java.awt.Graphics2D; 2 import java.awt.Rectangle; 3 import java.awt.geom.Ellipse2D; 4 import java.awt.geom.Line2D; 5 import java.awt.geom.Point2D; 6 7 /** 8 A car shape that can be positioned anywhere on the screen. 9 */ 10 public class Car 11 { 12 private int xLeft; 13 private int yTop; /** 16 Constructs a car with a given top left corner. x the x coordinate of the top left corner y the y coordinate of the top left corner 19 */ 20 public Car(int x, int y) 21 { 22 xLeft = x; 23 yTop = y; 24 } Continued ch03/car/Car.java Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall /** 27 Draws the car. g2 the graphics context 29 */ 30 public void draw(Graphics2D g2) 31 { 32 Rectangle body 33 = new Rectangle(xLeft, yTop + 10, 60, 10); 34 Ellipse2D.Double frontTire 35 = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10); 36 Ellipse2D.Double rearTire 37 = new Ellipse2D.Double(xLeft + 40, yTop + 20, 10, 10); // The bottom of the front windshield 40 Point2D.Double r1 41 = new Point2D.Double(xLeft + 10, yTop + 10); 42 // The front of the roof 43 Point2D.Double r2 44 = new Point2D.Double(xLeft + 20, yTop); 45 // The rear of the roof 46 Point2D.Double r3 47 = new Point2D.Double(xLeft + 40, yTop); Continued ch03/car/Car.java (cont.) Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall // The bottom of the rear windshield 49 Point2D.Double r4 50 = new Point2D.Double(xLeft + 50, yTop + 10); Line2D.Double frontWindshield 53 = new Line2D.Double(r1, r2); 54 Line2D.Double roofTop 55 = new Line2D.Double(r2, r3); 56 Line2D.Double rearWindshield 57 = new Line2D.Double(r3, r4); g2.draw(body); 60 g2.draw(frontTire); 61 g2.draw(rearTire); 62 g2.draw(frontWindshield); 63 g2.draw(roofTop); 64 g2.draw(rearWindshield); 65 } 66 } ch03/car/Car.java (cont.) Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall import javax.swing.JFrame; 2 3 public class CarViewer 4 { 5 public static void main(String[] args) 6 { 7 JFrame frame = new JFrame(); 8 9 frame.setSize(300, 400); 10 frame.setTitle("Two cars"); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CarComponent component = new CarComponent(); 14 frame.add(component); frame.setVisible(true); 17 } 18 } ch03/car/CarViewer.java Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall import java.awt.Graphics; 2 import java.awt.Graphics2D; 3 import javax.swing.JComponent; 4 5 /** 6 This component draws two car shapes. 7 */ 8 public class CarComponent extends JComponent 9 { 10 public void paintComponent(Graphics g) 11 { 12 Graphics2D g2 = (Graphics2D) g; Car car1 = new Car(0, 0); int x = getWidth() - 60; 17 int y = getHeight() - 30; Car car2 = new Car(x, y); car1.draw(g2); 22 car2.draw(g2); 23 } 24 } ch03/car/CarComponent.java Big Java by Cay Horstmann

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Filling Shapes Fill interior of shape g2.fill(shape); Set color for fills or strokes: g2.setColor(Color.red); Program that draws car CarIcon.java IconTester.java 41

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Defining a New Interface Type Use timer to move car shapes. Draw car with CarShape. Two responsibilities: o Draw shape o Move shape Define new interface type MoveableShape 42

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Implementing the Animation 1.Label contains icon that draws shape. 2.Timer action moves shape, calls repaint on label. 3.Label needs Icon, we have MoveableShape. 4.Supply ShapeIcon adapter class. 5.ShapeIcon.paintIcon calls MoveableShape.draw. 43

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 CRC Card for the MoveableShape Interface Type 44

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Defining a New Interface Type Name the methods to conform to standard library. public interface MoveableShape { void draw(Graphics2D g2); void translate(int dx, int dy); } CarShape class implements MoveableShape public class CarShape implements MoveableShape { public void translate(int dx, int dy) { x += dx; y += dy; }... } 45

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Implementing the Animation MoveableShape.java ShapeIcon.java AnimationTester.java CarShape.java BusShape.java 46

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Implementing the Animation 47

CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 End of Chapter 4 48