Chapter 14 Graphics

37
1 Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pea rson Education, Inc. All rights reserved. 0136012671 Chapter 14 Graphics

description

Chapter 14 Graphics. Motivations. If you want to draw shapes such as a bar chart, a clock, or a stop sign, as show in Figure 14.1, how do you do it?. Objectives. To understand Java coordinate systems (§14.2). To draw things using the methods in the Graphics class (§14.3). - PowerPoint PPT Presentation

Transcript of Chapter 14 Graphics

Page 1: Chapter 14 Graphics

1Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Chapter 14 Graphics

Page 2: Chapter 14 Graphics

2Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

MotivationsIf you want to draw shapes such as a bar chart, a clock, or a stop sign, as show in Figure 14.1, how do you do it?

Page 3: Chapter 14 Graphics

3Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Objectives To understand Java coordinate systems (§14.2). To draw things using the methods in the Graphics class (§14.3). To understand how and when a Graphics object is created (§14.3). To override the paintComponent method to draw things on a GUI

component (§14.4). To use a panel as a canvas to draw things (§14.5). To draw strings, lines, rectangles, ovals, arcs, and polygons

(§§14.6, 14.8-14.9). To obtain font properties using FontMetrics and know how to

center a message (§14.10). To display image in a GUI component (§14.13). To develop reusable GUI components FigurePanel, MessagePanel,

StillClock, and ImageViewer (§§14.7, 14.11, 14.12, 14.14).

Page 4: Chapter 14 Graphics

4Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Java Coordinate System

(0, 0) X Axis

Y Axis

(x, y)

x

y

Java Coordinate System

X Axis Conventional Coordinate System

(0, 0)

Y Axis

Page 5: Chapter 14 Graphics

5Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Each GUI Component Has its Own Coordinate System

(0, 0) Component c2

Component c1

(0, 0)

(0, 0) (x1, y1)

(x2, y2)

(x3, y3) Component c3 c3’s coordinate system

c2’s coordinate system

c1’s coordinate system

Page 6: Chapter 14 Graphics

6Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

The Graphics ClassYou can draw strings, lines, rectangles, ovals, arcs, polygons, and polylines, using the methods in the Graphics class.

java.awt.Graphics

+setColor(color: Color): void +setFont(font: Font): void +drawString(s: String, x: int, y: int): void +drawLine(x1: int, y1: int, x2: int, y2: int): void +drawRect(x: int, y: int, w: int, h: int): void

+fillRect(x: int, y: int, w: int, h: int): void

+drawRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void

+fillRoundRect(x: int, y: int, w: int, h: int, aw: int, ah: int): void

+draw3DRect(x: int, y: int, w: int, h: int, raised: boolean): void

+fill3DRect(x: int, y: int, w: int, h: int, raised: boolean): void

+drawOval(x: int, y: int, w: int, h: int): void

+fillOval(x: int, y: int, w: int, h: int): void

+drawArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void

+fillArc(x: int, y: int, w: int, h: int, startAngle: int, arcAngle: int): void

+drawPolygon(xPoints: int[], yPoints: int[], nPoints: int): void

+fillPolygon(xPoints: int[], yPoints: int[], nPoints: int): void

+drawPolygon(g: Polygon): void +fillPolygon(g: Polygon): void +drawPolyline(xPoints: int[], yPoints: int[],

nPoints: int): void

Sets a new color for subsequent drawings. Sets a new font for subsequent drwings. Draws a string starting at point (x, y). Draws a line from (x1, y1) to (x2, y2). Draws a rectangle with specified upper-left corner point at (x,

y) and width w and height h. Draws a filled rectangle with specified upper-left corner point

at (x, y) and width w and height h. Draws a round-cornered rectangle with specified arc width aw

and arc height ah. Draws a filled round-cornered rectangle with specified arc

width aw and arc height ah. Draws a 3-D rectangle raised above the surface or sunk into the

surface. Draws a filled 3-D rectangle raised above the surface or sunk

into the surface. Draws an oval bounded by the rectangle specified by the

parameters x, y, w, and h. Draws a filled oval bounded by the rectangle specified by the

parameters x, y, w, and h. Draws an arc conceived as part of an oval bounded by the

rectangle specified by the parameters x, y, w, and h. Draws a filled arc conceived as part of an oval bounded by the

rectangle specified by the parameters x, y, w, and h. Draws a closed polygon defined by arrays of x and y

coordinates. Each pair of (x[i], y[i]) coordinates is a point. Draws a filled polygon defined by arrays of x and y

coordinates. Each pair of (x[i], y[i]) coordinates is a point. Draws a closed polygon defined by a Polygon object. Draws a filled polygon defined by a Polygon object. Draws a polyline defined by arrays of x and y coordinates.

Each pair of (x[i], y[i]) coordinates is a point.

Page 7: Chapter 14 Graphics

7Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Obtaining Graphics ObjectThe Graphics class is an abstract class that provides a device-independent graphics interface for displaying figures and images on the screen on different platforms. Whenever a component (e.g., a button, a label, a panel) is displayed, a Graphics object is created for the component on the native platform. This object can be obtained using the getGraphics() method. For example, the graphics context for a label object jlblBanner can be obtained using

Graphics graphics = jlblBanner.getGraphics();

You can then apply the methods in the Graphics class to draw things on the label’s graphics context.

Page 8: Chapter 14 Graphics

8Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

A Drawing Example

Draw a line and a text

(0, 0)

(50, 50)

TestGetGraphics Run

Page 9: Chapter 14 Graphics

9Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Two Problems With the Preceding Example If you resize the frame, the line is gone. It is awkward to program because you have to make

sure that the component to be displayed before obtaining its graphics context using the getGraphics() method. For this reason, Lines 20 and 21 are placed after the frame is displayed in Line 17.

To fix the first problem, you need to know its cause. When you resize the frame, the JVM invokes the paintComponent method of a Swing component (e.g., a label) to redisplay the graphics on the component. Since you did not draw a line in the paintComponent method, the line is gone when the frame is resized. To permanently display the line, you need to draw the line in the paintComponent method.

Page 10: Chapter 14 Graphics

10Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

The paintComponent MethodThe paintComponent method is defined in JComponent, and its header is as follows:

protected void paintComponent(Graphics g)

This method, defined in the JComponent class, is invoked whenever the component is first displayed or redisplayed. The Graphics object g is created automatically by the JVM for every visible GUI component. The JVM obtains the Graphics object and passes it to invoke paintComponent.

Page 11: Chapter 14 Graphics

11Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

paintComponent ExampleIn order to draw things on a component (e.g., a JLabel), you need to declare a class that extends a Swing GUI component class and overrides its paintComponent method to specify what to draw. The first program in this chapter can be rewritten using paintComponent.

TestPaintComponent Run

Page 12: Chapter 14 Graphics

12Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing on Panels JPanel can be used to draw graphics (including text) and

enable user interaction. To draw in a panel, you create a new class that extends

JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings, draw geometric shapes, and view images on the panel.

TestPanelDrawing Run

Page 13: Chapter 14 Graphics

13Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Geometric Figures

Drawing Strings Drawing Lines Drawing Rectangles Drawing Ovals Drawing Arcs Drawing Polygons

Page 14: Chapter 14 Graphics

14Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Strings

(0, 0) (getWidth(), 0)

(getWidth(), getHeight()) (0, getHeight())

(x, y) s is display here

(0, 0) (getWidth(), 0)

(getWidth(), getHeight()) (0, getHeight())

(x1, y1)

(x2, y2)

drawLine(int x1, int y1, int x2, int y2);drawString(String s, int x, int y);

Page 15: Chapter 14 Graphics

15Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing RectanglesdrawRect(int x, int y, int w, int h);

fillRect(int x, int y, int w, int h);

Page 16: Chapter 14 Graphics

16Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Rounded RectanglesdrawRoundRect(int x, int y, int w, int h, int aw, int ah);

fillRoundRect(int x, int y, int w, int h, int aw, int ah);

Page 17: Chapter 14 Graphics

17Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing OvalsdrawOval(int x, int y, int w, int h);

fillOval(int x, int y, int w, int h);

Page 18: Chapter 14 Graphics

18Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Case Study: The FigurePanel Class This example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel.

FigurePanel +LINE = 1 +RECTANGLE = 2 +ROUND_RECTANGLE = 3 +OVAL = 4 -type: int -filled: boolean

+FigurePanel() +FigurePanel(type: int) +FigurePanel(type: int, filled: boolean) +getType(): int +setType(type: int): void +isFilled(): boolean +setFilled(filled: boolean): void

javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked

LINE, RECTANGLE, ROUND_RECTANGLE, and OVAL are constants.

Specifies the figure type (default: 1). Specifies whether the figure is filled (default: false).

Creates a default figure panel. Creates a figure panel with the specified type. Creates a figure panel with the specified type and filled property. Returns the figure type. Sets a new figure type. Checks whether the figure is filled with a color. Sets a new filled property.

FigurePanel

Page 19: Chapter 14 Graphics

19Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Test FigurePanelThis example develops a useful class for displaying various figures. The class enables the user to set the figure type and specify whether the figure is filled, and displays the figure on a panel.

TestFigurePanel Run

Page 20: Chapter 14 Graphics

20Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing ArcsdrawArc(int x, int y, int w, int h, int angle1, int angle2);fillArc(int x, int y, int w, int h, int angle1, int angle2);

Angles are in degree

Page 21: Chapter 14 Graphics

21Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Arcs Example

DrawArcs Run

Page 22: Chapter 14 Graphics

22Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Polygons and Polylinesint[] x = {40, 70, 60, 45, 20};int[] y = {20, 40, 80, 45, 60};g.drawPolygon(x, y, x.length);

g.drawPolyline(x, y, x.length);

Page 23: Chapter 14 Graphics

23Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Polygons Using the Polygon Class

Polygon polygon = new Polygon(); polygon.addPoint(40, 59); polygon.addPoint(40, 100); polygon.addPoint(10, 100); g.drawPolygon(polygon);

Page 24: Chapter 14 Graphics

24Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Polygons Example

DrawPolygon Run

Page 25: Chapter 14 Graphics

25Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Centering Display Using the FontMetrics Class You can display a string at any location in a panel. Can you display it centered? To do so, you need to use the FontMetrics class to measure the exact width and height of the string for a particular font. A FontMetrics can measure the following attributes:

public int getAscent() public int getDescent() public int getLeading()

getAscent()

getLeading()

getDescent()

getHeight()

public int getHeight() public int stringWidth(String str)

Page 26: Chapter 14 Graphics

26Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

The FontMetrics Class

FontMetrics is an abstract class. To get a FontMetrics object for a specific font, use the following getFontMetrics methods defined in the Graphics class:

·  public FontMetrics getFontMetrics(Font f)

Returns the font metrics of the specified font.

·  public FontMetrics getFontMetrics()

Returns the font metrics of the current font.

Page 27: Chapter 14 Graphics

27Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Welcome to Java stringWidth

stringAscent getHeight()

getWidth()

panel

TestCenterMessage Run

Page 28: Chapter 14 Graphics

28Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Case Study: MessagePanel

MessagePanel -xCoordinate: int -yCoordinate: int -centered: boolean -message: String -interval: int +MessagePanel() +MessagePanel(message: String) +moveLeft(): void +moveRight(): void +moveUp(): void +moveDown(): void

javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram

The x-Coordinate for the message (default 20). The y-Coordinate for the message (default 20). Specifies whether the message is displayed centered. The message to be displayed. The interval to move the message in the panel. Constructs a default message panel. Constructs a message panel with a specified string. Moves the message to the left. Moves the message to the right. Moves the message up. Moves the message down.

MessagePanel Run

This case study develops a useful class that displays a message in a panel. The class enables the user to set the location of the message, center the message, and move the message with the specified interval.

TestMessagePanel

Page 29: Chapter 14 Graphics

29Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Case Study: StillClock

DisplayClock RunStillClock

StillClock -hour: int -minute: int -second: int +StillClock() +StillClock(hour: int, minute: int,

second: int) +setCurrentTime(): void

javax.swing.JPanel -char token +getToken +setToken +paintComponet +mouseClicked

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram

The hour in the clock. The minute in the clock. The second in the clock. Constructs a default clock for the current time. Constructs a clock with a specified time.

Sets time to current time.

Page 30: Chapter 14 Graphics

30Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing ClockxEnd = xCenter + handLength sin()

yEnd = yCenter - handLength cos()

Since there are sixty seconds in one minute, the angle for the second hand is

second (2/60)

Page 31: Chapter 14 Graphics

31Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Clock, cont.xEnd = xCenter + handLength sin()

yEnd = yCenter - handLength cos()

The position of the minute hand is determined by the minute and second. The exact minute value combined with seconds is minute + second/60. For example, if the time is 3 minutes and 30 seconds. The total minutes are 3.5. Since there are sixty minutes in one hour, the angle for the minute hand is (minute + second/60) (2/60)

Page 32: Chapter 14 Graphics

32Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Drawing Clock, cont.xEnd = xCenter + handLength sin()

yEnd = yCenter - handLength cos()

Since one circle is divided into twelve hours, the angle for the hour hand is (hour + minute/60 + second/(60 60))) (2/12)

Page 33: Chapter 14 Graphics

33Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Displaying Image IconsYou learned how to create image icons and display image icons in labels and buttons. For example, the following statements create an image icon and display it in a label:

ImageIcon icon = new ImageIcon("image/us.gif");JLabel jlblImage = new JLabel(imageIcon);

An image icon displays a fixed-size image. To display an image in a flexible size, you need to use the java.awt.Image class. An image can be created from an image icon using the getImage() method as follows:

Image image = imageIcon.getImage();

Page 34: Chapter 14 Graphics

34Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Displaying ImagesUsing a label as an area for displaying images is simple and convenient, but you don't have much control over how the image is displayed. A more flexible way to display images is to use the drawImage method of the Graphics class on a panel. Four versions of the drawImage method are shown here.

java.awt.Graphics +drawImage(image: Image, x: int, y: int,

bgcolor: Color, observer: ImageObserver): void

+drawImage(image: Image, x: int, y: int, observer: ImageObserver): void

+drawImage(image: Image, x: int, y: int, width: int, height: int, observer: ImageObserver): void

+drawImage(image: Image, x: int, y: int, width: int, height: int, bgcolor: Color, observer: ImageObserver): void

Draws the image in a specified location. The image's top-left corner is at (x, y) in the graphics context's coordinate space. Transparent pixels in the image are drawn in the specified color bgcolor. The observer is the object on which the image is displayed. The image is cut off if it is larger than the area it is being drawn on.

Same as the preceding method except that it does not specify a background color.

Draws a scaled version of the image that can fill all of the available space in the specified rectangle.

Same as the preceding method except that it provides a solid background color behind the image being drawn.

Page 35: Chapter 14 Graphics

35Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Displaying Images ExampleThis example gives the code that displays an image from image/us.gif. The file image/us.gif is under the class directory. The Image from the file is created in the program. The drawImage method displays the image to fill in the whole panel, as shown in the figure.

RunDisplayImage

Page 36: Chapter 14 Graphics

36Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

Case Study: ImageViewer ClassDisplaying an image is a common task in Java programming. This case study develops a reusable component named ImageViewer that displays an image in a panel. The ImageViewer class contains the properties image, imageFilename, stretched, xCoordinate, and yCoordinate.

ImageViewer

-image: Image -stretched: boolean -xCoordinate: int -yCoordinate: int +ImageViewer() +ImageViewer(imageFile: String)

javax.swing.JPanel

Image in the image viewer.

True if the image is stretched in the viewer. x-coordinate of the upper-left corner of the image in the viewer. y-coordinate of the upper-left corner of the image in the viewer. Constructs an image viewer with no image. Constructs an image viewer with the specified image file.

The get and set methods for these data fields are provided in the class, but omitted in the UML diagram for brevity.

Page 37: Chapter 14 Graphics

37Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved. 0136012671

ImageView ExampleThis example gives an example that creates six images using the ImageViewer class.

RunSixFlags