Features of Java CS 3331 Sections 4.4.7 and 5.5.

Slides:



Advertisements
Similar presentations
Chapter 13 Graphics.
Advertisements

Applets and Graphics.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
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.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Graphics Programming. Introduction GOAL: Build the Indexer Client Event-driven vs. Sequential programs Terminology – Top-level windows are called “frame.
PHY-102 SAPIntroductory GraphicsSlide 1 Introductory Graphics In this section we will learn how about how to draw graphics on the screen in Java:  Drawing.
LAB SESSION 7 Graphical user interface Applet fundamentals Methods in applets Execution of an applet Graphics class.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
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 With Applets Feb 23, Applets There are three different types of executable java code. –Standalone application, which has main()
©2004 Brooks/Cole Applets Graphics & GUIs. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Graphical Programs Most applications these days are.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
Advanced Java Class GUI – part 1. Intro to GUI GUI = Graphical User Interface -- “Gooey” Just because it’s “gooey” does not mean you may write messy code.
Abstract Classes An abstract class is a class with partial implementation. It implements behaviors that are common to all subclasses, but defers to the.
Enahnced Digital Clock Applet Setting applet parameters in the web page. The applet tag in HTML:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Java Graphics Applets.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Applets and Graphics.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Drawing pictures with Java. JFrame: the basic Java window The swing package contains classes, objects and methods that can be used to create a consistent.
1 Features of Java CS 3331 Fall Outline  Abstract class  Interface  Application --- animation applets.
Chapter 16: Graphics. Objectives Learn about the paint() and repaint() methods Use the drawString() method to draw String s using various fonts and colors.
Abstract classes and Interfaces. Abstract classes.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
Applets Java API.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Java Applets What is an Applet? How do you create.
Applets CS 3331 Sections 3.3 & 4.7 of [Jia03].
Internet Software Development Applets Paul J Krause.
Java applet basics, loading & displaying images After this section, you should be able to : –Use the applet tag and applet parameters –Describe what a.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Arranging the border values of methods. import java.awt.*; import java.applet.Applet; public class Applet2 extends Applet { public void paint(Graphics.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved COS240 Object-Oriented Languages.
Applets & Graphics. Applets programs that run inside a browser Java platform-independence makes applets possible security restrictions: –cannot read or.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
Applets Applet is java program that can be embedded into HTML pages. Java applets runs on the java enabled web browsers such as mozilla and internet explorer.
Object Oriented Programming Lecture 5: Refactoring by Inheritance and Delegation - A simple Design Pattern for animation applets, A Generic Function Plotter.
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.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
The Drawing program – Java Applets
1 Windows program example import java.awt.*; import java.awt.event.*; public class wpexample extends Frame { public wpexample(String title) { super(title);
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Design Patterns: Design by Abstraction
Painting (Chapter 12) Java Certification Study Group January 25, 1999 Mark Roth.
Creating Graphics in Java CSE301 University of Sunderland Harry R Erwin, PhD.
Classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 Contents Introduction Applet Vs Application Security Restrictions on Applet A simple example “Hello World!” applet Compiling & Running Applet HTML document.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
CSI 3125, Preliminaries, page 1 Applet. CSI 3125, Preliminaries, page 2 Graphics Methods public abstract void drawString(String str, int x, int y): is.
CSI 3125, Preliminaries, page 1 AWT. CSI 3125, Preliminaries, page 2 AWT Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based.
More OOP. Extending other’s classes extend Java platform classes, e.g. class Applet public class MyApplet extends Applet { public void init() { } public.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
CSC 205 Programming II Lecture 4 Abstract Class. The abstract keyword indicate that a class is not instantiable Defining a type which will be specialized.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Introduction to Java Applets Will not cover Section 3.7 Thinking About Objects: Identifying.
1 CSC 551: Web Programming Spring 2004 Java Applets  Java vs. C++  instance vs. class variables, primitive vs. reference types, inheritance  graphical.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Java Applets. Introduction to Java and Java Applets Java applications Run in stand-alone mode No additional software required (such as a Web browser)
Intro to Graphics from Chapter 2 of Java Software Solutions
Topic: Applets Course : JAVA PROGRAMMING Paper Code: ETCS-307
User Interface Programming In Java
Fundamental of Java Programming
4.14 GUI and Graphics Case Study: Creating Simple Drawings (Cont.)
Presentation transcript:

Features of Java CS 3331 Sections 4.4.7 and 5.5

Outline Abstract class Interface Application --- animation applets

Motivation --- Drawing Board + init(): void + paint(g: Graphics) : void DrawingBoard Triangle + getX(): int + getY(): int + getColor(): Color + draw(g: Graphics): void - x: int - y: int - color: Color Shape 0..* shapes Circle Rectangle java.applet.Applet for (Shape s: shapes) { s.draw(g); }

Class Shape Q: What can be wrong with this implementation? public class Shape { private int x, y; private Color c; public Shape(int x, int y, Color c) { this.x = x; this.y = y; this.c = c; } public int getX() { return x; } public int getY() { return y; } public Color getColor { return c; } public void draw(Graphics g) { /* … */ } Q: What can be wrong with this implementation?

At Least Two Problems Instantiation of the Shape class, e.g., Shape s = new Shape(10, 10, Color.RED); Definition of the draw method Null implementation, i.e., public void draw(Graphics g) { } But, what if subclasses forget to override it? => not detected by Java compiler

Solution: Abstract Class public abstract class Shape { private int x, y; private Color c; protected Shape(int x, int y, Color c) { this.x = x; this.y = y; this.c = c; } public abstract void draw(Graphics g); // no body here! public int getX() { return x; } public int getY() { return y; } public Color getColor { return c; }

Abstract Classes? Classes that can’t be instantiated Used to define common properties that are to be inherited by subclasses Often provide partial implementations May include abstract methods, methods that have no body

How Abstract Classes Solve the Problems? Instantiation of abstraction classes is prohibited by Java compilers, e.g., new Shape(10, 10, Color.RED); // compilation error No implementation for abstract method Compilation error if concrete subclasses provide no implementations for inherited abstract methods

In Sum, Abstract Classes … Provide partial implementations to be inherited by subclasses May include abstract methods Are good for factoring out common properties among classes

Outline Abstract classes Interfaces Application --- animation applets

Interfaces Declare features to be supported by classes Provide no implementation (except for default method in Java 8) Only allow public abstract methods and constants (public static final fields) public interface ActionListener { void actionPerformed(ActionEvent event); }

Why Interfaces? To draw automobiles … 0..* Shape {abstract} DrawingBoard Vehicle Circle Rectangle Triangle Automobile

How to Draw Automobiles? By programming to the interface. + draw(g: Graphics) : void DrawableAutomobile Vehicle Automobile <<interface>> Drawable + draw(g: Graphics) : void 0..* DrawingBoard Shape {abstract} Circle Rectangle Triangle

In Sum, Interfaces … Good for establishing a well-defined boundary between modules (subsystems) Thus, make programs more reusable and maintainable

Abstract Classes vs. Interfaces Partial code vs. no code at all (except for default method in Java 8) Class vs. interface

Exercise Separate the display of DigitalClock to support various ways of displaying time, e.g., digital, analog, customized background, etc. Explain your design by drawing a UML class diagram. DigitalClock # timer: Timer # font: Font # color: Color + DigitalClock(): void + start(): void + stop(): void + paint(g: Graphics): void

Applications --- Animation Applets Enhanced digital clock applet Scrolling banner applet Initial version Double-buffered version

Enhanced Digital Clock Applet Setting applet parameters in the Web page <html> … <applet code=“DigitalClock2.class” width=“250” height=“80”> <param name=“color” value=“blue”> </applet> </html>

Getting Applet Parameters import java.awt.Color; public class DigitalClock2 extends DigitalClock { public void init() { String param = getParameter(“color”); if (“red”.equals(param)) { color = Color.RED; } else if (“blue”.equals(param)) { color = Color.BLUE; } else if (“yellow”.equals(param)) { color = Color.YELLOW; } /* … */ else { color = Color.GREEN; }

Animation Applets Enhanced digital clock applet Scrolling banner applet Initial version Double-buffered version

The java.awt.Graphics Class Class Graphics Represents graphics context, an abstraction of various drawing surfaces, e.g., screen, printer, off-screen image (an image stored in memory). Provide a rich set of graphics methods. drawString() drawLine() drawArc() fillArc() drawOval() fillOval() drawPolygon() fillPolygon() drawRect() fillRect() drawRoundRect() fillRoundRect()

Graphics Class (Cont.) Other methods setColor(color) set the current color setFont(font) set the current font setPaintMode() set the paint, or overwrite mode setXORMode(color) set the XOR mode getColor() get the current color getFont() get the current font getFontMetrics() get the font metrics of the current font getFontMetrics(font) get the font metrics for the specified font

The java.awt.FontMetrics Class Information about the rendering of a particular font on a particular screen. leading Up ascent height baseline descent width getAscent() getDescent() getHeight() getLeading() stringWidth(s)

Scrolling Banner Applet import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ScrollingBanner extends java.applet.Applet { <field declarations> public void init() { ... } public void paint(Graphics g) { ... } public void start() { ... } public void stop() { ... } }

Field Declarations protected String text; protected Font font = new java.awt.Font("Sans-serif", Font.BOLD, 24); protected Dimension dim; protected int x, y; protected int delay = 100; protected int offset = 1; protected Timer timer; // animation timer

Initialization public void init() { // get parameters "delay" and "text" String att = getParameter("delay"); if (att != null) { delay = Integer.parseInt(att); } att = getParameter("text"); text = att; } else { text = “Go Miners!”; // set initial position of the text dim = getSize(); x = dim.width; y = font.getSize(); // initialize animation timer timer = new Timer(delay, e -> repaint());

Painting the Current Frame (0, 0) length viewing area Go Miners! Go Miners! Go Miners! (-length, y) (x, y) (dim.width-1, y) (dim.width, y) leftmost position current position rightmost position

Painting the Current Frame (Cont.) public void paint(Graphics g) { // get the font metrics to determine the length of the text g.setFont(font); FontMetrics fm = g.getFontMetrics(); int length = fm.stringWidth(text); // adjust the position of text from the previous frame x = x - offset; // if the text is completely off to the left end // move the position back to the right end if (x < -length) { x = dim.width; } // set the pen color and draw the background g.setColor(Color.BLACK); g.fillRect(0, 0, dim.width, dim.height); // set the pen color, then draw the text g.setColor(Color.GREEN); g.drawString(text, x, y); }

The start() and stop() Methods public void start() { timer.start(); } public void stop() { timer.stop();

Exercise: Vertical Scrolling Define a subclass of ScrollingBanner, called ScrollingBanner3, that scrolls the banner vertically. Reuse code as much as possible and minimize code duplication.

How to Avoid Flickering? Flickering is caused by repaint() repaint() calls the update() method. The default update() method does the following: paint the whole area with the background color; set the foreground color; call the paint() method. The update() method is also called by the system to update windows. Solution: override the update() method use an off-screen image

Using Off-Screen Image Double buffering import java.awt.*; public class ScrollingBanner2 extends ScrollingBanner { protected Image image; // off-screen image protected Graphics offscreen; // off-screen graphics public update(Graphics g) { ... } public paint(Graphics g) { ... } }

Using Off-Screen Image (Cont.) public void update(Graphics g) { // create the offscreen image if it is the first time if (image == null) { image = createImage(dim.width, dim.height); offscreen = image.getGraphics(); } // draw the current frame into the off-screen image // using the paint method of the superclass super.paint(offscreen); // copy the off-screen image to the screen g.drawImage(image, 0, 0, this); } public void paint(Graphics g) { update(g);

Animation Applet Idiom Category Behavioral implementation idiom Intent For an applet to continuously update its appearance without user input or intervention Also known as Active Applet Applicability Use the Animation Applet Idiom to animate dynamic processes

Animation Applet Idiom (Cont.) import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AnimationApplet extends java.applet.Applet { protected Timer timer = null; protected int delay; public void init() { timer = new Timer(delay, e -> repaint()); }

Animation Applet Idiom (Cont.) public void start() { timer.start(); } public void stop() { timer.stop(); public void paint(Graphics g) { <paint the current frame> <other methods and fields> }

Exercise: Multiple Bouncing Balls Enhance the bouncing ball applet in Example 8.12 of the textbook to support multiple balls. Bounce several balls of different sizes. Change directions of balls when they collide with each other. Use an applet parameter, say numOfBalls, to specify the number of balls to bounce. Optionally, play a beep sound when a ball collides with another ball.