ITEC324 Principle of CS III

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

LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
Inner Classes. Nested Classes  An nested class is a class that is defined inside another class.  To this point we have only studied top-level classes.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
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.
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.
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.
Graphics Programming. In this class, we will cover: The difference between AWT and Swing Creating a frame Frame positioning Displaying information in.
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.
Swing Graphics ● Empty Swing containers have no visual appearance except for a background color ● Every JComponent must have a paintComponent method that.
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 ,
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
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.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Interfaces & Polymorphism part 2:
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,
Polymorphism and interfaces Horstmann ch 4. Outline Interface Polymorphism Function object Anonymous class User Interface Action Scope of variables (Large)
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
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.
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Graphics basic 1. 2 Objectives Understand Java coordinate systems. Draw things using the methods in the Graphics class. Override the paintComponent method.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
2.3 The Java API Documentation. What follows are the contents of the Java Application Programming Interface (API) Documentation for the system supplied.
Graphics Concepts CS 2302, Fall /17/20142 Drawing in Android.
Introduction to Java Chapter 8 - Introduction to Java Graphics1 Chapter 8 Introduction to Java Graphics.
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
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Chapter 4 Interface Types and Polymorphism Part 2.
Chapter 4 Interfaces and Polymorphism Object-Oriented Design & Patterns Cay S. Horstmann.
Interface types and Polymorphism
Modern Programming Tools And Techniques-I
“Form Ever Follows Function” Louis Henri Sullivan
Java Graphics CS 2511.
Chapter 4 Interface Types and Polymorphism Part 2
Building Java Programs
Chapter 4 Interface Types and Polymorphism Part 1
Ellen Walker Hiram College
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Inner Classes 11/14/ Dec-04 inner_classes.ppt.
ITEC324 Principle of CS III
Constructors, GUI’s(Using Swing) and ActionListner
Method of Classes Chapter 7, page 155 Lecture /4/6.
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
CiS 260: App Dev I Chapter 6: GUI and OOD.
ITEC324 Principle of CS III
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
ITEC324 Principle of CS III
Inner Classes.
Corresponds with Chapter 5
Chapter 4 Interface Types and Polymorphism Part 1
Presentation transcript:

ITEC324 Principle of CS III Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee ITEC324 Principle of CS III

Why? Interfaces Polymorphism A class defines a set of operations (the interface) and statements (implementation). Separating the interface concept from that of a class can help in the development of “generic” reusable code. Polymorphism Polymorphism: Ability to select different methods according to actual object type. Multiple classes can implement the same interface type so that it is possible to operate on a mixture of objects from any of these classes.

The Icon Interface Type public interface Icon { int getIconWidth(); int getIconHeight(); void paintIcon(Component c, Graphics g, int x, int y); }

Shape Interface Type & Polymorphism (1) 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); http://java.sun.com/j2se/1.3/docs/api/java/awt/Shape.html http://www.developer.com/tech/article.php/626101#_Complete_Program_Listing The Shape interface provides four groups of overloaded methods that make it possible to perform the following tasks: Get a bounding box that is guaranteed to enclose a specified Shape object. Determine if a specified Shape object completely contains a specified point or rectangle. Determine if a specified Shape intersects a specified rectangle Get a PathIterator object that can be used to obtain the path that makes up the boundary of a Shape object.

Shape Interface Type & Polymorphism (2) Drawing Rectangles and 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 Comments from Banton, Christopher [cbanton@radford.edu]: public static class Double extends Rectangle2D implements Serializable { ... } So "Double" is its own class, which is located within the Rectangle2D class for convenience. According to this webpage (http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html), it's called a nested top-level class.

Shape Interface Type & Polymorphism (3) Drawing Ellipses

Shape Interface Type & Polymorphism (4) 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);

Shape Interface Type & Polymorphism (5) Relationship btw Shape Interface and Classes

Shape Interface Type & Polymorphism (6) Drawing Text g2.drawString(text, x, y); x, y are base point coordinates

Shape Interface Type & Polymorphism (7) 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

Anonymous Classes No need to name objects that are used only once. Collections.sort(students, new StudentComparatorByName()); No need to name classes that are used only once. Comparator<Student> comp = new Comparator<Student>() { public int compare(Student student1, Student student2) { return student1.getName().compareTo(student2.getName()); } }; References: Generics in Java http://en.wikipedia.org/wiki/Generics_in_Java Comparator http://leepoint.net/notes-java/data/collections/comparators.html Comparable http://www.javadeveloper.co.in/java-example/java-comparable-example.html Comparable vs Comparator http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html

Factory Methods Anonymous class is commonly used in factory methods: public class Student { public static Comparator<Student> comparatorByName() {    return new Comparator<Student>()    {       public int compare(Student s1, Student s2) { . . . }    }; } } Neat arrangement if multiple comparators make sense (by name, by grade, ...) References: Static http://mindprod.com/jgloss/static.html

User Interface Action (1) Ch4/action1/ActionTest.java

User Interface Action (2) Accessing Variables from Enclosing Scope Method of Inner classes can access variables that are visible in the enclosing scope  e.g. actionPerformed method accesses the textField variable of the enclosing main method If an inner class accesses a local variable from an enclosing scope, the variable must be declared as final. final JTextField textField = new TextField(Field_WIDTH);

User Interface Action (3) To construct multiple objects of the same anonymous class, you must instantiate the anonymous class in a helper method (a factory method) and then call it multiple times. Note: you should declare parameters final Debug the following Code public static ActionListener createGreetingButtonListener(String message) { return new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText(message); } }; }

User Interface Action (4) Answer: public static ActionListener createGreetingButtonListener(final String message) { return new ActionListener() { public void actionPerformed(ActionEvent event) { textField.setText(message); } }; }

User Interface Action (5) Public class ActionTest { Public static void main(String[] args) … textField = new JTextField(FIELD_SIZE); helloButton.addActionListener( creatGreetingButtonListener(“Hello, World !”)); goodbyeButton. addActionListener( creatGreetingButtonListener(“Goodbye, World !”)); } // the helper method in the previous slide places here

Timers (1) Javax.swing package Timer generates a sequence of action events spaced apart at equal time interval, and notifies a designated action listener. ActionListener listener = ...; final int DELAY = 1000; // 1000 millisec = 1 sec Timer t = new Timer(DELAY, listener); t.start();  The start method returns immediately. A new thread of execution is started that issues action events in the specified frequency.

Timers (2) Ch4/timer/TimerTester.java

Designing an Interface Type (1) Public class ShapeIcon implements Icon { Public void paintIcon(Component c, Graphics g, int x, int y) Paint the shape } …

Designing an Interface Type (2) ShapeIcon icon = new ShapeIcon(…); JLabel label = new JLabel(icon); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent event) move the shape label.repaint(); } };

Designing an Interface Type (3) Use timer to Move car shapes Draw car with CarShape Two responsibilities: Draw shape Move shape Define new interface type MoveableShape : we can decoupled the animation from the car shape.

Designing an Interface Type (4) CRC Card for the MoveableShape Interface Type

Designing an Interface Type (5) 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; }    . . . }

Designing an Interface Type (6) 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

Designing an Interface Type (7) Implementing the Animation

Designing an Interface Type (8) Implementing the Animation Ch4/animation/MoveableShape.java Ch4/animation/ShapeIcon.java Ch4/animation/AnimationTester.java Ch4/animation/CarShape.java