37
1 Features of Java CS 3331 Sections 4.4.7 and 5.5

1 Features of Java CS 3331 Sections 4.4.7 and 5.5

Embed Size (px)

Citation preview

Page 1: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

1

Features of Java

CS 3331

Sections 4.4.7 and 5.5

Page 2: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

2

Outline

Abstract class Interface Application --- animation applets

Page 3: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

3

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);}

Page 4: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

4

Class Shape

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?

Page 5: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

5

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

Page 6: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

6

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; }}

Page 7: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

7

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

Page 8: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

8

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

Page 9: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

9

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

Page 10: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

10

Outline

Abstract classes Interfaces Application --- animation applets

Page 11: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

11

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);}

Page 12: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

12

Why Interfaces?

To draw automobiles …

DrawingBoard

Circle Rectangle Triangle

Vehicle

Automobile

0..* Shape{abstract}

Page 13: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

13

How to Draw Automobiles?

<<interface>>

Drawable

+ draw(g: Graphics) : void

By programming to the interface.

DrawingBoard

Circle Rectangle Triangle

0..*

Shape{abstract}

+ draw(g: Graphics) : void

DrawableAutomobile

Vehicle

Automobile

Page 14: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

14

In Sum, Interfaces …

Good for establishing a well-defined boundary between modules (subsystems)

Thus, make programs more reusable and maintainable

Page 15: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

15

Abstract Classes vs. Interfaces

Partial code vs. no code at all (except for default method in Java 8)

Class vs. interface

Page 16: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

16

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

Page 17: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

17

Applications --- Animation Applets

Enhanced digital clock applet Scrolling banner applet

Initial version Double-buffered version

Page 18: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

18

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>

Page 19: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

19

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; } }}

Page 20: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

20

Animation Applets

Enhanced digital clock applet Scrolling banner applet

Initial version Double-buffered version

Page 21: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

21

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

Page 22: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

22

Graphics Class (Cont.)

Other methods

setColor(color) set the current colorsetFont(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

Page 23: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

23

The java.awt.FontMetrics Class

getAscent() getDescent() getHeight() getLeading() stringWidth(s)

Upwidth

height

leading

ascent

descentbaseline

Information about the rendering of a particular font on a particular screen.

Page 24: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

24

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() { ... }}

Page 25: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

25

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

Page 26: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

26

Initialization

public void init() { // get parameters "delay" and "text" String att = getParameter("delay"); if (att != null) { delay = Integer.parseInt(att); } att = getParameter("text"); if (att != null) { text = att; } else { text = “Go Miners!”; } // set initial position of the text dim = getSize(); x = dim.width; y = font.getSize();

// initialize animation timertimer = new Timer(delay, e -> repaint());

Page 27: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

27

Painting the Current Frame

Go Miners!Go Miners! Go Miners!

length viewing area

(dim.width, y)(dim.width-1, y)(-length, y) (x, y)

(0, 0)

leftmost position rightmost positioncurrent position

Page 28: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

28

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); }

Page 29: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

29

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

Page 30: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

30

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.

Page 31: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

31

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

Page 32: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

32

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) { ... }}

Page 33: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

33

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); }

Page 34: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

34

Animation Applet Idiom Category

Behavioral implementation idiom Intent

For an applet to continuously update its appearance without user input or intervention

Also known asActive Applet

ApplicabilityUse the Animation Applet Idiom to animate dynamic processes

Page 35: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

35

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());}

Page 36: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

36

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>}

Page 37: 1 Features of Java CS 3331 Sections 4.4.7 and 5.5

37

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.