chapter 7 (graphics and animation) - nyu

38
7-1 Copyright (c) 1999-2004 N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets

Upload: others

Post on 23-Mar-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 7 (Graphics and animation) - NYU

7-1 Copyright (c) 1999-2004 N. Afshartous

Contents1. Classes and Objects

2. Inheritance

3. Interfaces

4. Exceptions and Error Handling

5. Intro to Concurrency

6. Concurrency in Java

7. Graphics and Animation8. Applets

Page 2: Chapter 7 (Graphics and animation) - NYU

7-2 Copyright (c) 1999-2004 N. Afshartous

Chapter 7: Graphics and ImagesAfter this chapter you will be able to:

- Create windows

- Draw lines, shapes, and text

- Download and display images

- Use double-buffering and threads to create animation

Page 3: Chapter 7 (Graphics and animation) - NYU

7-3 Copyright (c) 1999-2004 N. Afshartous

Creating a Window• Create a subclass of class Frame

import java.awt.Frame;

public class Main extends Frame {public static void main (String [] args) {

Frame f = new Main();f.resize(200,200); // set width and heightf.show(); // display window

}}

Page 4: Chapter 7 (Graphics and animation) - NYU

7-4 Copyright (c) 1999-2004 N. Afshartous

Displayed Window

Page 5: Chapter 7 (Graphics and animation) - NYU

7-5 Copyright (c) 1999-2004 N. Afshartous

Inheritance Hierchy• Class Frame has several superclasses

Object

Component

Container

Window

Frame

Page 6: Chapter 7 (Graphics and animation) - NYU

7-6 Copyright (c) 1999-2004 N. Afshartous

Drawing Onto A Window• Define methodpaint and use the passed

graphics context to draw onto the window

• The methods for drawing are defined in class Graphics

import java.awt.Frame;import java.awt.Graphics;

public class Main extends Frame {public static void main (String [] args) {...}

public void paint (Graphics g) {g.drawString("hello there", 10,10);

// x, y}

}

Page 7: Chapter 7 (Graphics and animation) - NYU

7-7 Copyright (c) 1999-2004 N. Afshartous

Displayed Windowx = 0y = 0

x

y

Page 8: Chapter 7 (Graphics and animation) - NYU

7-8 Copyright (c) 1999-2004 N. Afshartous

Redrawing• Redrawing is required:

– initially when window appears

– after resizing

– after part of the window becomes exposed after being hidden

• System calls update to redraw

• Default implementation of update clears screen and calls paint

• Program can request a redraw to callingrepaint

Page 9: Chapter 7 (Graphics and animation) - NYU

7-9 Copyright (c) 1999-2004 N. Afshartous

Methods Called for Redraw• Program can call repaint and the system can

call update

public void update(Graphics g);

public void paint(Graphics g);

public void repaint();

Page 10: Chapter 7 (Graphics and animation) - NYU

7-10 Copyright (c) 1999-2004 N. Afshartous

Drawing Text• Method drawString of class Graphics

displays a string at the specified coordinates using the current font

public void drawString(String x, int x, int y);

Page 11: Chapter 7 (Graphics and animation) - NYU

7-11 Copyright (c) 1999-2004 N. Afshartous

Creating Fonts• Fonts may be created by calling theFont class

constructor

• Name is one of: Helvetica, TimesRoman, Courier, Dialog, Symbol

• Font property is the sum of any of the following constants:– Font.BOLD

– Font.ITALIC

– Font.PLAIN

public Font (String name, int property, int size);

Page 12: Chapter 7 (Graphics and animation) - NYU

7-12 Copyright (c) 1999-2004 N. Afshartous

Changing Font• New Font is passed to Graphics.setFont

public void paint (Graphics g) {Font hvFont = new Font("Helvetica", Font.BOLD, 20);g.setFont(hvFont);g.drawString("hello there", 20,20);

}

Page 13: Chapter 7 (Graphics and animation) - NYU

7-13 Copyright (c) 1999-2004 N. Afshartous

Measuring Text• Can get aFontMetrics object by calling

Graphics.getFontMetrics

• Class FontMetrics has methods:

– returns the width of a string in a given font

– returns the height of a line of text in a given font

• and others

public int getHeight();

public int stringWidth(String str);

Page 14: Chapter 7 (Graphics and animation) - NYU

7-14 Copyright (c) 1999-2004 N. Afshartous

Getting Window Size• Can call inherited method size of class

Component

– Returns aDimension object which encapsulates the currentwidth and height

of the window

– Dimension.height

– Dimension.width

public Dimension size();

Page 15: Chapter 7 (Graphics and animation) - NYU

7-15 Copyright (c) 1999-2004 N. Afshartous

Example• Centering a string inside a window

public void paint (Graphics g) {Dimension d = size(); // resizing is OKFont hvFont = new Font("Helvetica", Font.BOLD, 20);FontMetrics hvMetrics = g.getFontMetrics(hvFont);g.setFont(hvFont);int x = d.width/2 -

hvMetrics.stringWidth("hello there")/2;int y = d.height/2 - hvMetrics.getHeight()/2;g.drawString("hello there", x, y);

}

Page 16: Chapter 7 (Graphics and animation) - NYU

7-16 Copyright (c) 1999-2004 N. Afshartous

Displayed Window

Page 17: Chapter 7 (Graphics and animation) - NYU

7-17 Copyright (c) 1999-2004 N. Afshartous

Drawing Shapes• Class Graphics defines the following methods:

public abstract void drawLine(int x1, int y1, int x2, int y2)

public abstract void drawOval(int x, int y,int width, int height)

public abstract void drawPolygon (int xPoints[], int yPoints[], int nPoints)

public void drawRect(int x, int y,int width, int height);

Page 18: Chapter 7 (Graphics and animation) - NYU

7-18 Copyright (c) 1999-2004 N. Afshartous

Drawing Circles• Pass coordinates of upper left corner of box

containing the circle, width, and heightpublic void paint (Graphics g) {

g.drawOval(0,0,30,30);// x, y of upper left corner// width, height

}

Page 19: Chapter 7 (Graphics and animation) - NYU

7-19 Copyright (c) 1999-2004 N. Afshartous

Filling Circle• Each draw method has a fill version

public void paint (Graphics g) {g.fillOval(0,0,30,30);

// x, y of upper left corner// width, height

}

Page 20: Chapter 7 (Graphics and animation) - NYU

7-20 Copyright (c) 1999-2004 N. Afshartous

Color• Class Color defines the following constants:

public final static Color black; public final static Color blue;public final static Color cyan; public final static Color darkGray;public final static Color gray;public final static Color green;public final static Color lightGray;public final static Color magenta;public final static Color orange;public final static Color pink;public final static Color red;public final static Color white;public final static Color yellow;

Page 21: Chapter 7 (Graphics and animation) - NYU

7-21 Copyright (c) 1999-2004 N. Afshartous

Creating New Colors• Can create a new color by calling aColor

class constructor

• Or by calling class Color methods:

public Color(float red, float green, float blue);public Color(int rgb);public Color(int red, int green, int blue);

public Color brighter();public Color darker();

Page 22: Chapter 7 (Graphics and animation) - NYU

7-22 Copyright (c) 1999-2004 N. Afshartous

Setting Current Color• Call method setColor of class Graphics

public void paint (Graphics g) {g.setColor(Color.cyan);g.fillOval(0,0,30,30);

}

Page 23: Chapter 7 (Graphics and animation) - NYU

7-23 Copyright (c) 1999-2004 N. Afshartous

Images• Images can be displayed by:

– calling Toolkit.getImage to load an image

– and then by callingGraphics.drawImage

to display the image

public abstract Image getImage(URL url);public abstract Image getImage(String filename);

public abstract boolean drawImage (Image img, int x, int y, ImageObserver observer)

Page 24: Chapter 7 (Graphics and animation) - NYU

7-24 Copyright (c) 1999-2004 N. Afshartous

Interface ImageObserver• Class Component (and it’s subclasses)

implement interface ImageObserver

Object

ComponentimplementsImageObserver

Container

Window

Frame

Page 25: Chapter 7 (Graphics and animation) - NYU

7-25 Copyright (c) 1999-2004 N. Afshartous

ImageObserver• Interface ImageObserver

public interface java.awt.image.ImageObserver {// flags for the infoflags argument to imageUpdate// flags are used to indicate status loadingpublic final static int ABORT; // was abortedpublic final static int ALLBITS; // loading compl ete

public final static int ERROR; // error loadingpublic final static int FRAMEBITS; // frame loadedpublic final static int HEIGHT; // height availablepublic final static int PROPERTIES // props availab lepublic final static int SOMEBITS; // partially loade dpublic final static int WIDTH; // width available

public abstract booleanimageUpdate(Image img, int infoflags,int x, int y, int width, int height);

}

Page 26: Chapter 7 (Graphics and animation) - NYU

7-26 Copyright (c) 1999-2004 N. Afshartous

Image Loading• Calling Graphics.drawImage spawns a

background thread to manage the image loading

• Calling drawImage may not display anything image if the image has not finished loading

• The imageUpdate method of theImageObserver parameter to drawImage is repeatedly called by the background thread during image loading

• Default implementation ofimageUpdate calls update to redraw

Page 27: Chapter 7 (Graphics and animation) - NYU

7-27 Copyright (c) 1999-2004 N. Afshartous

Displaying An Image

public void paint (Graphics g) {Image img =

Toolkit.getDefaultToolkit().getImage("nick.jpg");g.drawImage(img, 0, 0, null);

}

• getDefaultToolkit returns a Toolkit

object

• null is passed to drawImage

as the ImageObserver to indicate no calls toimageUpdate are necessary

Page 28: Chapter 7 (Graphics and animation) - NYU

7-28 Copyright (c) 1999-2004 N. Afshartous

Animation• Make a separate thread object for each animated

figure

• The code to position the animated figures is then calculated independently by each thread

• Later we’ll incorporate double-buffering to eliminate flicker

• Flicker results from clearing the entire screen in between redraws and makes the animation look less smooth

Page 29: Chapter 7 (Graphics and animation) - NYU

7-29 Copyright (c) 1999-2004 N. Afshartous

Animated Circlesclass AnimCircle extends Thread {

private Point upperLeft;public static int width; // window width

public AnimCircle (int x, int y) {upperLeft = new Point(x,y);

}

public synchronized Point getPosition () { return upperLeft;

}

private synchronized void move () {upperLeft.x++; if (upperLeft.x >= width) upperLeft.x = 0;

}

public void run () {...}}

Page 30: Chapter 7 (Graphics and animation) - NYU

7-30 Copyright (c) 1999-2004 N. Afshartous

Circles’s Next Position

class AnimCircle extends Thread {...public void run () {

while (true) {move();

try {Thread.sleep(20);

} catch (InterruptedException e) {}}

}}

• run repeatedly calls move to update position

Page 31: Chapter 7 (Graphics and animation) - NYU

7-31 Copyright (c) 1999-2004 N. Afshartous

Class Animimport java.awt.*; import java.util.Vector;

public class Anim extends Frame{static Vector circles = new Vector();

public static void main (String [] args) {AnimCircle c1 = new AnimCircle(0,40);AnimCircle c2 = new AnimCircle(0,80);circles.addElement(c1);circles.addElement(c2);AnimCircle.width = 300;Frame f = new Anim();f.resize(300,300);f.show(); // start circle threadsc1.start(); c2.start();

}public void paint (Graphics g) {...}

}

Page 32: Chapter 7 (Graphics and animation) - NYU

7-32 Copyright (c) 1999-2004 N. Afshartous

Drawing Circles• Paint draws the circles and then calls repaint

import java.awt.*; import java.util.Vector;

public class Anim extends Frame{...

public void paint (Graphics g) {for (int i = 0; i < circles.size(); i++) {

Point upperLeft = ((AnimCircle) circles.elementAt(i)).getPosition();g.drawOval(upperLeft.x, upperLeft.y, 20, 20);

}repaint();

}}

Page 33: Chapter 7 (Graphics and animation) - NYU

7-33 Copyright (c) 1999-2004 N. Afshartous

Animated Scene• Circles move toward the right and then start

again from the left

Page 34: Chapter 7 (Graphics and animation) - NYU

7-34 Copyright (c) 1999-2004 N. Afshartous

Double-Buffering• Use an offscreen image for drawing

• After drawing next scene on the offscreen image display offscreen image on window

• Double-buffering eliminates flicker

Off Screen Image Window

overlay

DrawDraw

Page 35: Chapter 7 (Graphics and animation) - NYU

7-35 Copyright (c) 1999-2004 N. Afshartous

Off Screen Image• Declare variables for the off screen image and

associated Graphics context

import java.awt.*; import java.util.Vector;

public class Anim extends Frame{

static Vector circles = new Vector();static int imageWidth = 300;static int imageHeight = 300;static Image offScreenImage;static Graphics offg;...

Page 36: Chapter 7 (Graphics and animation) - NYU

7-36 Copyright (c) 1999-2004 N. Afshartous

Drawing Onto Off Screen Image• Override update so window will not be cleared

import java.awt.*; import java.util.Vector;

public class Anim extends Frame{...

// must override update or window will be cleared// between redraws resulting in flicker!!!

public void update (Graphics g) {paint(g);

}

public void paint (Graphics g) {...

} }

Page 37: Chapter 7 (Graphics and animation) - NYU

7-37 Copyright (c) 1999-2004 N. Afshartous

Paint

public void paint (Graphics g) {if (offg == null) {

offScreenImage = createImage(imageWidth,imageHeight);offg = offScreenImage.getGraphics();

}offg.setColor(Color.white); // clear backgroundoffg.fillRect(0, 0, imageWidth, imageHeight);offg.setColor(Color.black);for (int i = 0; i < circles.size(); i++) {

Point upperLeft = ((AnimCircle) circles.elementAt(i)).getPosition();

offg.fillOval(upperLeft.x, upperLeft.y, 40, 40);}g.drawImage(offScreenImage, 0, 0, null);repaint();

}

• Draw on off screen image then overlay

Page 38: Chapter 7 (Graphics and animation) - NYU

7-38 Copyright (c) 1999-2004 N. Afshartous

It’s Exercise Time