COMP Lecture Notes for Week 4 - Interfaces and Polymorphism. Chapter Topics. Displaying an Image. Displaying an Image

Similar documents
Outline. Anonymous Classes. Annoucements. CS1007: Object Oriented Design and Programming in Java

Outline HW2. Feedback. CS1007: Object Oriented Design and Programming in Java

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

It is a promise that your class will implement certain method with certain signatures.

ICOM 4015: Advanced Programming

9/2/2011. Chapter Goals

2/9/2012. Chapter Three: Implementing Classes. Chapter Goals

Programming Graphics (P1 2006/2007)

H212 Introduction to Software Systems Honors

Building Graphical User Interfaces. GUI Principles

Lecture 5: Java Graphics

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

Building Graphical User Interfaces. Overview

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

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

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Lecture 3: Java Graphics & Events

Window Interfaces Using Swing Objects

AP CS Unit 11: Graphics and Events

Interfaces and Polymorphism Advanced Programming

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

Java Programming Lecture 6

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

Introduction to the JAVA UI classes Advanced HCI IAT351

Chapter 9. Interfaces and Polymorphism. Chapter Goals. Chapter Goals. Using Interfaces for Code Reuse. Using Interfaces for Code Reuse

class BankFilter implements Filter { public boolean accept(object x) { BankAccount ba = (BankAccount) x; return ba.getbalance() > 1000; } }

We are on the GUI fast track path

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

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

MIT AITI Swing Event Model Lecture 17

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

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!

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

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

Window Interfaces Using Swing Objects

Programmierpraktikum

Chapter 2 An Introduction to Objects and Classes. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

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

Object-Oriented Programming Design. Topic : Graphics Programming GUI Part I

Swing from A to Z Some Simple Components. Preface

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

Graphical User Interfaces 2

Object-oriented programming in Java (2)

2IS45 Programming

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 :) )

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

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

Chapter 2 Using Objects. Copyright 2014 by John Wiley & Sons. All rights reserved. 1

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

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

Swing Programming Example Number 2

Chapter 2 Using Objects

Chapter 6 Using Objects

SampleApp.java. Page 1

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

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

Graphic User Interfaces. - GUI concepts - Swing - AWT

Design patterns for graphical user interface applications

GUI (Graphic User Interface) Programming. Part 2 (Chapter 8) Chapter Goals. Events, Event Sources, and Event Listeners. Listeners

User interfaces and Swing

2. (True/False) All methods in an interface must be declared public.

Graphical User Interface

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

Class 16: The Swing Event Model

CMP 326 Midterm Fall 2015

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

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

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

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

Programming Language Concepts: Lecture 8

SINGLE EVENT HANDLING

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

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

Abstract, Interface, GUIs. Ch. 11 & 16

Programming graphics

Graphical User Interfaces. Comp 152

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

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

Part I: Learn Common Graphics Components

Animation Part 2: MoveableShape interface & Multithreading

Graphical User Interface (GUI)

Section Basic graphics

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

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

PIC 20A GUI with swing

JAVA NOTES GRAPHICAL USER INTERFACES

8/23/2011. Chapter Goals

2/9/2012. Chapter Two: Using Objects. Chapter Goals

Graphical User Interfaces

CSIS 10A Assignment 7 SOLUTIONS

G51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions

Graphical User Interfaces 2

Check out ThreadsIntro project from SVN. Threads and Animation

encompass a group of features for building Graphical User Interfaces (GUI).

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

CSC 1214: Object-Oriented Programming

Introduction. Introduction

Transcription:

COMP 303 - Lecture Notes for Week 4 - Interfaces and Polymorphism Slides edited from, Object-Oriented Design Patterns, by Cay S. Horstmann Original slides available from: http://www.horstmann.com/design_and_patterns.html Modifications made by Laurie Hendren, McGill University Topics this week: Interfaces and Polymorphism, Chapter 4 Using ant for project builds and maintenance next... [Slide 1]... Chapter Topics Displaying an Image Polymorphism Drawing Shapes The Comparable Interface The Comparator Interface Anonymous Classes Frames and User Interface Components User Interface Actions Timers Designing an Interface previous start next... [Slide 2]... Displaying an Image Use JOptionPane to display message: JOptionPane.showMessageDialog(null, "Hello, World!"); Note icon to the left Displaying an Image Can specify arbitrary image file JOptionPane.showMessageDialog( null, "Hello, World!", "Message", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("globe.gif")); previous start next... [Slide 3]... previous start next... [Slide 4]...

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 The Icon Interface Type public interface Icon int geticonwidth(); int geticonheight(); void painticon(component c, Graphics g, int x, int y) previous start next... [Slide 6]... previous start next... [Slide 5]... Interface Types No implementation Implementing class must supply implementation of all methods Ch4/icon2/MarsIcon.java showmessagedialog expects Icon object Ok to pass MarsIcon Ch4/icon2/IconTest.java previous start next... [Slide 7]... 02: import java.awt.geom.*; 03: import javax.swing.*; 04: 05: /** 06: An icon that has the shape of the planet Mars. 07: */ 08: public class MarsIcon implements Icon 09: 10: /** 11: Constructs a Mars icon of a given size. 12: @param asize the size of the icon 13: */ 14: public MarsIcon(int asize) 15: 16: size = asize; 17: 18: 19: public int geticonwidth() 20: 21: return size; 22: 23: 24: public int geticonheight() 25: 26: return size; 27: 28: 29: public void painticon(component c, Graphics g, int x, int y) 30: 31: Graphics2D g2 = (Graphics2D) g; 32: Ellipse2D.Double planet = new Ellipse2D.Double(x, y, 33: size, size); 34: g2.setcolor(color.red); 35: g2.fill(planet); 36: 37: 38: private int size; 39:

01: import javax.swing.*; 02: 03: public class IconTest 04: 05: public static void main(string[] args) 06: 07: JOptionPane.showMessageDialog( 08: null, 09: "Hello, Mars!", 10: "Message", 11: JOptionPane.INFORMATION_MESSAGE, 12: new MarsIcon(50)); 13: System.exit(0); 14: 15: 16: The Icon Interface Type and Implementing Classes previous start next... [Slide 8]... Polymorphism public static void showmessagedialog(...icon anicon) showmessagedialog shows icon message OK button showmessagedialog must compute size of dialog width = icon width + message size + blank size How do we know the icon width? int width = anicon.geticonwidth(); Polymorphism showmessagedialog doesn t know which icon is passed ImageIcon? MarsIcon?...? 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 previous start next... [Slide 10]... previous start next... [Slide 9]...

A Variable of Interface Type Polymorphism Which geticonwidth method is called? Could be MarsIcon.getIconWidth ImageIcon.getIconWidth... Depends on object to which anicon reference points, e.g. showmessagedialog(..., new MarsIcon(50)) previous start next... [Slide 11]... Polymorphism: Select different methods according to actual object type previous start next... [Slide 12]... Benefits of Polymorphism Loose coupling showmessagedialog decoupled from ImageIcon Doesn t need to know about image processing Extensibility Client can supply new icon types previous start next... [Slide 13]... 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); previous start next... [Slide 14]...

Drawing Rectangles and Ellipses Drawing Ellipses Rectangle2D.Double constructed with top left corner width height g2.draw(new Rectangle2D.Double(x, y, width, height)); For Ellipse2D.Double, specify bounding box previous start next... [Slide 15]... previous start next... [Slide 16]... Drawing Line Segments Relationship Between Shape Classes 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); previous start next... [Slide 17]... previous start next... [Slide 18]...

Drawing Text g2.drawstring(text, x, y); x, y are base point coordinates Filling Shapes Fill interior of shape g2.fill(shape); Set color for fills or strokes: g2.setcolor(color.red); Program that draws car Ch4/icon3/CarIcon.java previous start next... [Slide 19]... previous start next... [Slide 20]... 02: import java.awt.geom.*; 03: import javax.swing.*; 04: 05: /** 06: An icon that has the shape of a car. 07: */ 08: public class CarIcon implements Icon 09: 10: /** 11: Constructs a car of a given width. 12: @param width the width of the car 13: */ 14: public CarIcon(int awidth) 15: 16: width = awidth; 17: 18: 19: public int geticonwidth() 20: 21: return width; 22: 23: 24: public int geticonheight() 25: 26: return width / 2; 27: 28: 29: public void painticon(component c, Graphics g, int x, int y) 30: 31: Graphics2D g2 = (Graphics2D) g; 32: Rectangle2D.Double body 33: = new Rectangle2D.Double(x, y + width / 6, 34: width - 1, width / 6); 35: Ellipse2D.Double fronttire 36: = new Ellipse2D.Double(x + width / 6, y + width / 3, 37: width / 6, width / 6); 38: Ellipse2D.Double reartire 39: = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3, 40: width / 6, width / 6); 41: 42: // the bottom of the front windshield 43: Point2D.Double r1 44: = new Point2D.Double(x + width / 6, y + width / 6); 45: // the front of the roof 46: Point2D.Double r2 47: = new Point2D.Double(x + width / 3, y); 48: // the rear of the roof 49: Point2D.Double r3 50: = new Point2D.Double(x + width * 2 / 3, y); 51: // the bottom of the rear windshield 52: Point2D.Double r4 53: = new Point2D.Double(x + width * 5 / 6, y + width / 6); 54: 55: Line2D.Double frontwindshield 56: = new Line2D.Double(r1, r2); 57: Line2D.Double rooftop 58: = new Line2D.Double(r2, r3); 59: Line2D.Double rearwindshield 60: = new Line2D.Double(r3, r4); 61: 62: g2.fill(fronttire); 63: g2.fill(reartire); 64: g2.setcolor(color.red); 65: g2.fill(body); 66: g2.draw(frontwindshield); 67: g2.draw(rooftop); 68: g2.draw(rearwindshield); 69: 70: 71: private int width; 72: 73: 74:

The Comparable Interface Type Collections has static sort method: ArrayList a =... Collections.sort(a); Objects in list must implement the Comparable interface type public interface Comparable int compareto(object other); The Comparable Interface Type sort method compares and rearranges elements if (object1.compareto(object2) > 0)... String class implements Comparable interface type: lexicographic (dictionary) order Country class: compare countries by area Ch4/sort1/Country.java Ch4/sort1/CountrySortTest.java previous start next... [Slide 22]... object1.compareto(object2) returns Negative number if object1 less than object2 0 if objects identical Positive number if object1 greater than object2 previous start next... [Slide 21]... 01: /** 02: A country with a name and area. 03: */ 04: public class Country implements Comparable 05: 06: /** 07: Constructs a country. 08: @param aname the name of the country 09: @param anarea the area of the country 10: */ 11: public Country(String aname, double anarea) 12: 13: name = aname; 14: area = anarea; 15: 16: 17: /** 18: Gets the name of the country. 19: @return the name 20: */ 21: public String getname() 22: 23: return name; 24: 25: 26: /** 27: Gets the area of the country. 28: @return the area 29: */ 30: public double getarea() 31: 32: return area; 33: 34: 35: 36: /** 37: Compares two countries by area. 38: @param otherobject the other country 39: @return a negative number if this country has a smaller 40: area than othercountry, 0 if the areas are the same, 41: a positive number otherwise 42: */ 43: public int compareto(object otherobject) 44: 45: Country other = (Country) otherobject; 46: if (area < other.area) return -1; 47: if (area > other.area) return 1; 48: return 0; 49: 50: 51: private String name; 52: private double area; 53:

01: import java.util.*; 02: 03: public class CountrySortTest 04: 05: public static void main(string[] args) 06: 07: ArrayList countries = new ArrayList(); 08: countries.add(new Country("Uruguay", 176220)); 09: countries.add(new Country("Thailand", 514000)); 10: countries.add(new Country("Belgium", 30510)); 11: Collections.sort(countries); 12: // now the array list is sorted by area 13: for (int i = 0; i < countries.size(); i++) 14: 15: Country c = (Country) countries.get(i); 16: System.out.println(c.getName() + " " + c.getarea()); 17: 18: 19: 20: 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(object object1, Object object2); Pass comparator object to sort: Collections.sort(list, comp); previous start next... [Slide 23]... The Comparator interface type Ch4/sort2/CountryComparatorByName.java Ch4/sort2/ComparatorTest.java Comparator object is a function object This particular comparator object has no state State can be useful, e.g. flag to sort in ascending or descending order 01: import java.util.*; 02: 03: public class CountryComparatorByName implements Comparator 04: 05: public int compare(object object1, Object object2) 06: 07: Country country1 = (Country) object1; 08: Country country2 = (Country) object2; 09: return country1.getname().compareto(country2.getname()); 10: 11: previous start next... [Slide 24]...

01: import java.util.*; 02: 03: public class ComparatorTest 04: 05: public static void main(string[] args) 06: 07: ArrayList countries = new ArrayList(); 08: countries.add(new Country("Uruguay", 176220)); 09: countries.add(new Country("Thailand", 514000)); 10: countries.add(new Country("Belgium", 30510)); 11: Comparator comp = new CountryComparatorByName(); 12: Collections.sort(countries, comp); 13: // now the array list is sorted by name 14: for (int i = 0; i < countries.size(); i++) 15: 16: Country c = (Country) countries.get(i); 17: System.out.println(c.getName() + " " + c.getarea()); 18: 19: 20: 21: 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(object obj1, Object obj2) Country country1 = (Country)obj1; Country country2 = (Country)obj2; return country1.getname().compareto(country2.getname()); ; previous start next... [Slide 25]... Anonymous Classes anonymous new expression: defines anonymous class that implements Comparator defines compare method of that class constructs one object of that class Cryptic syntax for very useful feature previous start next... [Slide 26]... Anonymous Classes Commonly used in factory methods: public static Comparator comparatorbyname() return new Comparator() public int compare(object o1, Object o2)... ; Collections.sort(a, Country.comparatorByName()); Neat arrangement if multiple comparators make sense (by name, by area,...) previous start next... [Slide 27]...

Frames Frame window has decorations title bar close box provided by windowing system JFrame frame = new JFrame(); frame.pack(); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.show(); previous start next... [Slide 28]... Adding Components Construct components JButton hellobutton = new JButton("Say Hello"); Set content pane layout Container contentpane = frame.getcontentpane(); container.setlayout(new FlowLayout()); Add components to content pane contentpane.add(hellobutton); Ch4/frame/FrameTest.java previous start next... [Slide 29]... 02: import javax.swing.*; 03: 04: public class FrameTest 05: 06: public static void main(string[] args) 07: 08: JFrame frame = new JFrame(); 09: 10: JButton hellobutton = new JButton("Say Hello"); 11: JButton goodbyebutton = new JButton("Say Goodbye"); 12: 13: final int FIELD_WIDTH = 20; 14: JTextField textfield = new JTextField(FIELD_WIDTH); 15: textfield.settext("click a button!"); 16: 17: Container contentpane = frame.getcontentpane(); 18: contentpane.setlayout(new FlowLayout()); 19: 20: contentpane.add(hellobutton); 21: contentpane.add(goodbyebutton); 22: contentpane.add(textfield); 23: 24: frame.setdefaultcloseoperation(jframe.exit_on_close); 25: frame.pack(); 26: frame.show(); 27: 28: 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 int actionperformed(actionevent event); Listeners are notified when button is clicked previous start next... [Slide 30]...

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"); ); Accessing Variables from Enclosing Scope Remarkable: Inner class can access variables from enclosing scope e.g. textfield Can access enclosing instance fields, local variables Local variables must be marked final final JTextField textfield =...; previous start next... [Slide 32]... When button is clicked, text field is set previous start next... [Slide 31]... User Interface Actions 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!"); Ch4/action1/ActionTest.java previous start next... [Slide 33]... 02: import java.awt.event.*; 03: import javax.swing.*; 04: 05: public class ActionTest 06: 07: public static void main(string[] args) 08: 09: JFrame frame = new JFrame(); 10: 11: final int FIELD_WIDTH = 20; 12: final JTextField textfield = new JTextField(FIELD_WIDTH); 13: textfield.settext("click a button!"); 14: 15: JButton hellobutton = new JButton("Say Hello"); 16: 17: hellobutton.addactionlistener(new 18: ActionListener() 19: 20: public void actionperformed(actionevent event) 21: 22: textfield.settext("hello, World!"); 23: 24: ); 25: 26: 27: JButton goodbyebutton = new JButton("Say Goodbye"); 28: 29: goodbyebutton.addactionlistener(new 30: ActionListener() 31: 32: public void actionperformed(actionevent event) 33: 34: textfield.settext("goodbye, World!"); 35: 36: ); 37: 38: Container contentpane = frame.getcontentpane(); 39: contentpane.setlayout(new FlowLayout()); 40: 41: contentpane.add(hellobutton);

42: contentpane.add(goodbyebutton); 43: contentpane.add(textfield); 44: 45: frame.setdefaultcloseoperation(jframe.exit_on_close); 46: frame.pack(); 47: frame.show(); 48: 49: Constructing Related Actions Write helper method that constructs objects Pass variable information as parameters Declare parameters final public static ActionListener creategreetingbuttonlistener( final String message) return new ActionListener() public void actionperformed(actionevent event) textfield.settext(message); ; previous start next... [Slide 34]... 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 Ch4/timer/TimerTest.java previous start next... [Slide 35]... 02: import java.awt.event.*; 03: import java.util.*; 04: import javax.swing.*; 05: import javax.swing.timer; 06: 07: /** 08: This program shows a clock that is updated once per second. 09: */ 10: public class TimerTest 11: 12: public static void main(string[] args) 13: 14: JFrame frame = new JFrame(); 15: 16: final int FIELD_WIDTH = 20; 17: final JTextField textfield = new JTextField(FIELD_WIDTH); 18: 19: Container contentpane = frame.getcontentpane(); 20: contentpane.setlayout(new FlowLayout()); 21: contentpane.add(textfield); 22: 23: ActionListener listener = new 24: ActionListener() 25: 26: public void actionperformed(actionevent event) 27: 28: Date now = new Date(); 29: textfield.settext(now.tostring()); 30: 31: ; 32: final int DELAY = 1000; 33: // milliseconds between timer ticks 34: Timer t = new Timer(DELAY, listener); 35: t.start(); 36: 37: frame.setdefaultcloseoperation(jframe.exit_on_close); 38: frame.pack(); 39: frame.show(); 40: 41:

Defining a New Interface Type Use timer to move car shapes Draw car with CarShape Two responsibilities: CRC Card for the MoveableShape Interface Type Draw shape Move shape Define new interface type MoveableShape previous start next... [Slide 36]... previous start next... [Slide 37]... 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); Implementing the Animation Label contains icon that draws shape Timer action moves shape, calls repaint on label Label needs Icon, we have MoveableShape Supply ShapeIcon adapter class ShapeIcon.paintIcon calls MoveableShape.draw previous start next... [Slide 39]... public class CarShape implements MoveableShape public void translate(int dx, int dy) x += dx; y += dy;... previous start next... [Slide 38]...

Implementing the Animation Ch4/animation/MoveableShape.java Ch4/animation/ShapeIcon.java Ch4/animation/AnimationTest.java Ch4/animation/CarShape.java previous start next... [Slide 40]... 02: 03: /** 04: A shape that can be moved around. 05: */ 06: public interface MoveableShape 07: 08: /** 09: Draws the shape. 10: @param g2 the graphics context 11: */ 12: void draw(graphics2d g2); 13: /** 14: Moves the shape by a given amount. 15: @param dx the amount to translate in x-direction 16: @param dy the amount to translate in y-direction 17: */ 18: void translate(double dx, double dy); 19: 02: import java.util.*; 03: import javax.swing.*; 04: 05: /** 06: An icon that contains a moveable shape. 07: */ 08: public class ShapeIcon implements Icon 09: 10: public ShapeIcon(MoveableShape shape, 11: int width, int height) 12: 13: this.shape = shape; 14: this.width = width; 15: this.height = height; 16: 17: 18: public int geticonwidth() 19: 20: return width; 21: 22: 23: public int geticonheight() 24: 25: return height; 26: 27: 28: public void painticon(component c, Graphics g, int x, int y) 29: 30: Graphics2D g2 = (Graphics2D) g; 31: shape.draw(g2); 32: 33: 34: private int width; 35: private int height; 36: private MoveableShape shape; 37: 38: 39: 02: import java.awt.event.*; 03: import javax.swing.*; 04: 05: /** 06: This program implements an animation that moves 07: a car shape. 08: */ 09: public class AnimationTest 10: 11: public static void main(string[] args) 12: 13: JFrame frame = new JFrame(); 14: 15: final MoveableShape shape 16: = new CarShape(0, 0, CAR_WIDTH); 17: 18: ShapeIcon icon = new ShapeIcon(shape, 19: ICON_WIDTH, ICON_HEIGHT); 20: 21: final JLabel label = new JLabel(icon); 22: Container contentpane = frame.getcontentpane(); 23: contentpane.setlayout(new FlowLayout()); 24: contentpane.add(label); 25: 26: frame.setdefaultcloseoperation(jframe.exit_on_close); 27: frame.pack(); 28: frame.show(); 29: 30: final int DELAY = 100; 31: // milliseconds between timer ticks 32: Timer t = new Timer(DELAY, new 33: ActionListener() 34: 35: public void actionperformed(actionevent event) 36: 37: shape.translate(1, 0); 38: label.repaint(); 39: 40: ); 41: t.start();

42: 43: 44: private static final int ICON_WIDTH = 400; 45: private static final int ICON_HEIGHT = 100; 46: private static final int CAR_WIDTH = 100; 47: 02: import java.awt.geom.*; 03: import java.util.*; 04: 05: /** 06: A car that can be moved around. 07: */ 08: public class CarShape implements MoveableShape 09: 10: /** 11: Constructs a car item. 12: @param x the left of the bounding rectangle 13: @param y the top of the bounding rectangle 14: @param width the width of the bounding rectangle 15: */ 16: public CarShape(int x, int y, int width) 17: 18: this.x = x; 19: this.y = y; 20: this.width = width; 21: 22: 23: public void translate(double dx, double dy) 24: 25: x += dx; 26: y += dy; 27: 28: 29: public void draw(graphics2d g2) 30: 31: Rectangle2D.Double body 32: = new Rectangle2D.Double(x, y + width / 6, 33: width - 1, width / 6); 34: Ellipse2D.Double fronttire 35: = new Ellipse2D.Double(x + width / 6, y + width / 3, 36: width / 6, width / 6); 37: Ellipse2D.Double reartire 38: = new Ellipse2D.Double(x + width * 2 / 3, y + width / 3, 39: width / 6, width / 6); 40: 41: // the bottom of the front windshield 42: Point2D.Double r1 43: = new Point2D.Double(x + width / 6, y + width / 6); 44: // the front of the roof 45: Point2D.Double r2 46: = new Point2D.Double(x + width / 3, y); 47: // the rear of the roof 48: Point2D.Double r3 49: = new Point2D.Double(x + width * 2 / 3, y); 50: // the bottom of the rear windshield 51: Point2D.Double r4 52: = new Point2D.Double(x + width * 5 / 6, y + width / 6); 53: Line2D.Double frontwindshield 54: = new Line2D.Double(r1, r2); 55: Line2D.Double rooftop 56: = new Line2D.Double(r2, r3); 57: Line2D.Double rearwindshield 58: = new Line2D.Double(r3, r4); 59: 60: g2.draw(body); 61: g2.draw(fronttire); 62: g2.draw(reartire); 63: g2.draw(frontwindshield); 64: g2.draw(rooftop); 65: g2.draw(rearwindshield); 66: 67: 68: private int x; 69: private int y; 70: private int width; 71: Implementing the Animation previous start... [Slide 41]...