Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)

Slides:



Advertisements
Similar presentations
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Advertisements

Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
CPSC 2100 University of Tennessee at Chattanooga – Fall 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 4: Interface Types.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Review CSC 171 FALL 2004 LECTURE 21. Topics Objects and Classes Fundamental Types Graphics and Applets Decisions Iteration Designing Classes Testing and.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
1 Interface Types & Polymorphism & introduction to graphics programming in Java.
Design Patterns and Graphical User Interfaces Horstmann ,
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington User Interface COMP 112 #30.
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
Computer Science 209 The Strategy Pattern I: Comparisons and Layouts.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Interfaces & Polymorphism part 2:
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
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,
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
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
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
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.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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)
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
Chapter 4 Interface Types and Polymorphism: Graphics, Timer, Animation.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
CS 151: Object-Oriented Design October 1 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
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,
Lecture 33: More Graphical User Interface (GUI) Announcements & Review Read Ch GU1 & GU2 Cohoon & Davidson Ch 14 Reges & Stepp Lab 10 set game due 4/26.
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.
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.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
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:
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Dental Payment Application.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Chapter 4 Interface Types and Polymorphism Part 2.
Chapter 4 Interfaces and Polymorphism Object-Oriented Design & Patterns Cay S. Horstmann.
GUIs and Events Rick Mercer.
Interface types and Polymorphism
ITEC324 Principle of CS III
“Form Ever Follows Function” Louis Henri Sullivan
Chapter 4 Interface Types and Polymorphism Part 2
Chapter 4 Interface Types and Polymorphism Part 1
Ellen Walker Hiram College
Timer class and inner classes
Advanced Programming in Java
Constructors, GUI’s(Using Swing) and ActionListner
ITEC324 Principle of CS III
Chapter 4 Interface Types and Polymorphism Part 1
Presentation transcript:

Polymorphism and interfaces Horstmann ch 4

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

Displaying an image JOptionPane.showMessageDialog(null, ”Welcome!”);

Displaying an image Use image from file JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new ImageIcon(”au.jpg”));

Displaying an image Draw image JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new CarIcon(100));

Interface How can an image from a file be used in the same way as an image specified by a drawing algorithm? By using an interface! Interface Icon abstracts the relevant properties public interface Icon { int getIconWidth(); int getIconHeight(); void paintIcon(Component c, Graphics g, int x, int y); } Interface contain no implementation of methods

Interface JOptionPane.showMessageDialog( null, ”Welcome!”, ”Message”, JOptionPane.INFORMATION_MESSAGE, new CarIcon(100)); public static void showMessageDialog( Component parentComponent, Objekt message, String title, int messageType, Icon icon) showMessageDialog knows about au-logo and car picture ONLY as something implementing interface Icon

Interface Implementing class must supply implementation of all methods public class CarIcon implements Icon { public int getIconWidth() {... } public int getIconHeight() {... } public void paintIcon(Component c, Graphics g, int x, int y) {... } }

QUIZ Which assertions are true? 1.none 2.A 3.B 4.C 5.A, B 6.A, C 7.B, C 8.A, B, C 9.I don’t know A.An interface specifies method headers B.An interface specifies method bodies C.Comparable implements interface String

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

Decoupling showMessageDialog expects an Icon object showMessageDialog need not know whether the actual type of the object is CarIcon or ImageIcon or …

Polymorphic variable public static void showMessageDialog( …, Icon anIcon) 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 methods getIconWidth, getIconHeight, etc.

Method Polymorphism public static void showMessageDialog( …, Icon anIcon) showMessageDialog must compute size of dialog width = icon width + message size + blank size How do we know the icon width? int width = anIcon.getIconWidth(); 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)) Polymorphism: Select different methods according to actual object type

QUIZ Which lines result in errors? 1.none 2.a 3.b 4.a+b 5.I don’t know Sad s; s = new Choleric(); a) s.cry(); b) s.laugh();

QUIZ Which lines result in errors? 1.none 2.a 3.b 4.c 5.a+b 6.a+c 7.b+c 8.a+b+c 9.I don’t know Sad s; Choleric c; c = new Choleric(); a) s = c; b) c = s; c) c = (Choleric) s;

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

Example: sorting Sort by name –AntiChrist, 108 min –Gran Torino, 116 min –Mænd der hader kvinder, 155 min –Slumdog Millionaire, 120 min Sort by duration –AntiChrist, 108 min –Gran Torino, 116 min –Slumdog Millionaire, 120 min –Mænd der hader kvinder, 155 min

Comparable interface type Collections has static sort method. For a being an array list Collections.sort(a); Objects in list must implement the Comparable interface type public interface Comparable { int compareTo(T other); } object1.compareTo(object2) returns –Negative number if object1 less than object2 –0 if objects identical –Positive number if object1 greater than object2 How can we sort Films by both name and length? Can't implement Comparable twice! dIntProg

Comparator interface type Comparator interface type gives added flexibility public interface Comparator { int compare(T object1, T object2); } Comparator object is a function object Pass comparator object to sort: Collections.sort(list, comp);

Strategy ArrayList films =... ; Comparator comp1 = new NameComp(); Collections.sort(films, comp1); Comparator comp2 = new LenghtComp(); Collections.sort(films, comp2);

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

Anonymous Classes No need to name classes that are used only once Comparator comp = new Comparator () { public int compare(Film f1, Film f2) { return f1.getName().compareTo(f2.getName()); } }; Same as Comparator comp = new NameComp(); public class NameComp implements Comparator { public int compare(Film f1, Film f2) { return f1.getName().compareTo(f2.getName()); }

Anonymous Classes Commonly used in factory methods: public static Comparator comparatorByName() { return new Comparator () { public int compare(Film c1, Film c2) {...} }; } Collections.sort(a, Film.comparatorByName()); Neat arrangement if multiple comparators make sense (by name, by length,...)

QUIZ Which lines result in errors? 1.None (or missing code) 2.a 3.b 4.a+b 5.I don’t know Sad s; a) s = new Sad() { b) public void laugh() {...} };

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

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.setVisible(true);

Adding Components Construct components JButton helloButton = new JButton("Say Hello"); Set frame layout frame.setLayout(new FlowLayout()); Add components to frames frame.add(helloButton);

User Interface Actions Add listener object(s) to button public interface ActionListener { void actionPerformed(ActionEvent event); } Listeners are notified when button is clicked

User Interface Actions helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } ); When button is clicked, text field is set

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!");

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

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 =...;... helloButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText("Hello, World"); } ); final

QUIZ public class Quiz { private final TextField display = …; public ActionListener createButtonListener( final String message) { final String prefix = “NOTE: “; return new ActionListener() { public void actionPerformed(ActionEvent event) { display.setText(prefix + message); } }; } 1.None 2.a 3.b 4.c 5.a, b 6.a, c 7.b, c 8.a, b, c 9.I don’t know a b c Which of the 3 ”final” can be removed without errors?

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

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

Defining a New Interface Type Use timer to move car shapes Draw car with CarShape Two responsibilities: –Draw shape –Move shape Define new interface type MoveableShape

Implementing the Animation

Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large) example Graphics in Java

Graphics in Java… How is the car Icon drawn? 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);

Drawing Rectangles Rectangle2D.Double constructed with –top left corner –width –height g2.draw( new Rectangle2D.Double(x, y, width, height) );

Drawing Ellipses For Ellipse2D.Double, specify bounding box

Drawing Line Segments Point2D.Double is a point in the plane Line2D.Double joins two 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);

Relationship Between Shape Classes

Drawing Text g2.drawString("Message", 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 (uses class CarIcon )