0% found this document useful (0 votes)
6 views57 pages

Graphics Java2d

Chapter 11 covers Java's graphics capabilities, including the Java 2D API for drawing 2D shapes, controlling colors and fonts. It discusses graphics contexts, color manipulation, and font control, along with practical examples of using these features in Java applications. The chapter also includes optional case studies on designing interfaces with UML.

Uploaded by

lithubco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views57 pages

Graphics Java2d

Chapter 11 covers Java's graphics capabilities, including the Java 2D API for drawing 2D shapes, controlling colors and fonts. It discusses graphics contexts, color manipulation, and font control, along with practical examples of using these features in Java applications. The chapter also includes optional case studies on designing interfaces with UML.

Uploaded by

lithubco
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 57

Chapter 11 - Graphics and Java 2D

Outline
11.1 Introduction
11.2 Graphics Contexts and Graphics Objects
11.3 Color Control
11.4 Font Control
11.5 Drawing Lines, Rectangles and Ovals
11.6 Drawing Arcs
11.7 Drawing Polygons and Polylines
11.8 The Java 2D API
11.9 Java 2D Shapes
11.10 (Optional Case Study) Thinking About Objects:
Designing Interfaces with the UML

 2002 Prentice Hall, Inc. All rights reserved.


11.1 Introduction

• Java’s graphics capabilities


– Drawing 2D shapes
– Controlling colors
– Controlling fonts
• Java 2D API
– More sophisticated graphics capabilities
• Drawing custom 2D shapes
• Filling shapes with colors and patterns

 2002 Prentice Hall, Inc. All rights reserved.


Fig 11.1 Some classes and
interfaces used in this chapter from
Java’s original graphics capabilities
and from the Java2D API
java.lang.Object Key

java.awt.Color class

java.awt.Component interface

java.awt.Font

java.awt.FontMetrics

java.awt.Graphics

java.awt.Polygon

Classes and interfa ces from the J ava2D API


java.awt.Graphics2D
java.awt.Paint
java.awt.BasicStroke java.awt.Shape
java.awt.GradientPaint java.awt.Stroke
java.awt.TexturePaint

java.awt.geom.GeneralPath

java.awt.geom.Line2D

java.awt.geom.RectangularShape

java.awt.geom.Arc2D

java.awt.geom.Ellipse2D

java.awt.geom.Rectangle2D

java.awt.geom.RoundRectangle2D

 2002 Prentice Hall, Inc. All rights reserved.


11.1 Introduction

• Java’s coordinate system


– Scheme for identifying all points on screen
– Upper-left corner has coordinates (0,0)
– Coordinate point composed of x-coordinate and y-coordinate

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.2 Java coordinate system.
Units are measured in pixels.

+x
(0, 0) X a xis

(x, y)

+y

Y a xis

 2002 Prentice Hall, Inc. All rights reserved.


11.2 Graphics Context and Graphics
Objects
• Graphics context
– Enables drawing on screen
– Graphics object manages graphics context
• Controls how information is drawn
– Class Graphics is abstract
• Cannot be instantiated
• Contributes to Java’s portability
– Class Component method paint takes Graphics object
public void paint( Graphics g )
– Called through method repaint

 2002 Prentice Hall, Inc. All rights reserved.


11.3 Color Control

• Class Color
– Defines methods and constants for manipulating colors
– Colors are created from red, green and blue components
• RGB values

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.3 Color class static
constants and RGB values.
Color Constant Color RGB value
public final static Color orange orange 255, 200, 0
public final static Color pink pink 255, 175, 175
public final static Color cyan cyan 0, 255, 255
public final static Color magenta magenta 255, 0, 255
public final static Color yellow yellow 255, 255, 0
public final static Color black black 0, 0, 0
public final static Color white white 255, 255, 255
public final static Color gray gray 128, 128, 128
public final static Color lightGray light gray 192, 192, 192
public final static Color darkGray dark gray 64, 64, 64
public final static Color red red 255, 0, 0
public final static Color green green 0, 255, 0
public final static Color blue blue 0, 0, 255
Fig. 11.3 Color c lass static c onstants and RGB values

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.4 Color methods and color-
related Graphics methods.

Method Description
public Color( int r, int g, Creates a color based on red, green and blue contents
int b ) expressed as integers from 0 to 255.
public Color( float r, Creates a color based on red, green and blue contents
float g, float b ) expressed as floating-point values from 0.0 to 1.0.
public int getRed() Returns a value between 0 and 255 representing the red
// Color class content.
public int getGreen() Returns a value between 0 and 255 representing the green
// Color class content.
public int getBlue() Returns a value between 0 and 255 representing the blue
// Color class content.
public Color getColor() Returns a Color object representing the current color for the
// Graphics class graphics context.
public void setColor( Color Sets the current color for drawing with the graphics context.
c ) // Graphics class
Fig. 11.4 Color methods and c olor-related Graphics methods.

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.5: ShowColors.java
// Demonstrating Colors.
Outline
3
4 // Java core packages
5 import java.awt.*; ShowColors.java
6 import java.awt.event.*;
7
8 // Java extension packages Line 23
9 import javax.swing.*;
10
11 public class ShowColors extends JFrame { Line 29
12
13 // constructor sets window's title bar string and dimensions Line 30
14 public ShowColors()
15 {
16 super( "Using colors" ); Paint window when Line 31
17 application begins
18 setSize( 400, 130 );
19 setVisible( true );
execution
20 }
21
22 // draw rectangles and Strings in different colors Method setColor
23 public void paint( Graphics g )
24 {
sets color’s RGB value
25 // call superclass's paint method
26 super.paint( g ); Method fillRect creates filled
27
28 // set new drawing color using integers rectangle at specified coordinates
29 g.setColor( new Color( 255, 0, 0 ) ); using current RGB value
30 g.fillRect( 25, 25, 100, 20 );
31 g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
32
33 // set new drawing color using floats
Method drawString draw colored
34 g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
35 g.fillRect( 25, 50, 100, 20 ); text at specified coordinates
 2002 Prentice Hall, Inc. All rights reserved.
36 g.drawString( "Current RGB: " + g.getColor(), 130, 65 ); Outline
37
38 // set new drawing color using static Color objects
39 g.setColor( Color.blue );
40 g.fillRect( 25, 75, 100, 20 ); ShowColors.java
41 g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
42 Lines 39 and 44
43 // display individual RGB values Use constant in class Color
44 Color color = Color.magenta;
45 g.setColor( color ); to specify current color
46 g.fillRect( 25, 100, 100, 20 );
47 g.drawString( "RGB values: " + color.getRed() + ", " +
48 color.getGreen() + ", " + color.getBlue(), 130, 115 );
49 }
50
51 // execute application
52 public static void main( String args[] )
53 {
54 ShowColors application = new ShowColors();
55
56 application.setDefaultCloseOperation(
57 JFrame.EXIT_ON_CLOSE );
58 }
59
60 } // end class ShowColors

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.6: ShowColors2.java
// Demonstrating JColorChooser.
Outline
3
4 // Java core packages
5 import java.awt.*; ShowColors2.java
6 import java.awt.event.*;
7
8 // Java extension packages Line 35
9 import javax.swing.*;
10
11 public class ShowColors2 extends JFrame { Line 35
12 private JButton changeColorButton;
13 private Color color = Color.lightGray;
14 private Container container;
15
16 // set up GUI
17 public ShowColors2()
18 {
19 super( "Using JColorChooser" ); JColorChooser allows
20
21 container = getContentPane();
user to choose from among
22 container.setLayout( new FlowLayout() ); several colors
23
24 // set up changeColorButton and register its event handler
25 changeColorButton = new JButton( "Change Color" );
26
27 changeColorButton.addActionListener(
28
29 // anonymous inner class
30 new ActionListener() {
31
32 // display JColorChooser when user clicks button static method
33 public void actionPerformed( ActionEvent event ) showDialog displays
34 {
the color chooser dialog
35 color = JColorChooser.showDialog(
 2002 Prentice Hall, Inc. All rights reserved.
36 ShowColors2.this, "Choose a color", color ); Outline
37
38 // set default color, if no color is returned
39 if ( color == null )
40 color = Color.lightGray; ShowColors2.java
41
42 // change content pane's background color
43 container.setBackground( color );
44 }
45
46 } // end anonymous inner class
47
48 ); // end call to addActionListener
49
50 container.add( changeColorButton );
51
52 setSize( 400, 130 );
53 setVisible( true );
54 }
55
56 // execute application
57 public static void main( String args[] )
58 {
59 ShowColors2 application = new ShowColors2();
60
61 application.setDefaultCloseOperation(
62 JFrame.EXIT_ON_CLOSE );
63 }
64
65 } // end class ShowColors2

 2002 Prentice Hall, Inc. All rights reserved.


Outline

ShowColors2.java

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.7 The HSB and RGB of the
JColorChooser dialog

 2002 Prentice Hall, Inc. All rights reserved.


11.4 Font Control

• Class Font
– Contains methods and constants for font control
– Font constructor takes three arguments
• Font name
– Monospaced, SansSerif, Serif, etc.
• Font style
– Font.PLAIN, Font.ITALIC and Font.BOLD
• Font size
– Measured in points (1/72 of inch)

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.8 Font methods, constants
and font-related Graphics methods

Method or constant Description


public final static int PLAIN A constant representing a plain font style.
// Font class
public final static int BOLD A constant representing a bold font style.
// Font class
public final static int ITALIC A constant representing an italic font style.
// Font class
public Font( String name, int Creates a Font object with the specified font, style and size.
style, int size )
public int getStyle() Returns an integer value indicating the current font style.
// Font class
public int getSize() Returns an integer value indicating the current font size.
// Font class
public String getName() Returns the current font name as a string.
// Font class
public String getFamily() Returns the font’s family name as a string.
// Font class
Fig. 11.8 Font methods, c onstants and font-related Graphics methods (Part 1 of 2).

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.8 Font methods, constants
and font-related Graphics methods
(Part 2).

Method or constant Description


public boolean isPlain() Tests a font for a plain font style. Returns true if the
// Font class font is plain.
public boolean isBold() Tests a font for a bold font style. Returns true if the
// Font class font is bold.
public boolean isItalic() Tests a font for an italic font style. Returns true if the
// Font class font is italic.
public Font getFont() Returns a Font object reference representing the current
// Graphics class font.
public void setFont( Font f ) Sets the current font to the font, style and size specified
// Graphics class by the Font object reference f.
Fig. 11.8 Font methods, c onstants and font-related Graphics methods (Part 2 of 2).

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.9: Fonts.java
// Using fonts
Outline
3
4 // Java core packages
5 import java.awt.*; Fonts.java
6 import java.awt.event.*;
7
8 // Java extension packages Line 30
9 import javax.swing.*;
10
11 public class Fonts extends JFrame { Line 31
12
13 // set window's title bar and dimensions
14 public Fonts()
15 {
16 super( "Using fonts" );
17
18 setSize( 420, 125 );
19 setVisible( true );
20 }
21
22 // display Strings in different fonts and colors
23 public void paint( Graphics g )
24 {
25 // call superclass's paint method Method setFont sets current font
26 super.paint( g );
27
28 // set current font to Serif (Times), bold, 12pt
29 // and draw a string
30 g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
31 g.drawString( "Serif 12 point bold.", 20, 50 ); Draw text using current font
32
33 // set current font to Monospaced (Courier),
34 // italic, 24pt and draw a string
35 g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
 2002 Prentice Hall, Inc. All rights reserved.
36 g.drawString( "Monospaced 24 point italic.", 20, 70 ); Outline
37
38 // set current font to SansSerif (Helvetica),
39 // plain, 14pt and draw a string
40 g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) ); Fonts.java
41 g.drawString( "SansSerif 14 point plain.", 20, 90 );
42
43 // set current font to Serif (times), bold/italic,
Line 41
44 // 18pt and draw a string
45 g.setColor( Color.red ); Set font to SansSerif 14-point
Lines 46-47plain
46 g.setFont(
47 new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
48 g.drawString( g.getFont().getName() + " " +
49 g.getFont().getSize() +
50 " point bold italic.", 20, 110 );
51 }
Set font to Serif 18-point bold italic
52
53 // execute application
54 public static void main( String args[] )
55 {
56 Fonts application = new Fonts();
57
58 application.setDefaultCloseOperation(
59 JFrame.EXIT_ON_CLOSE );
60 }
61
62 } // end class Fonts

 2002 Prentice Hall, Inc. All rights reserved.


11.4 Font Control (cont.)

• Font metrics
– Height
– Descent (amount character dips below baseline)
– Ascent (amount character rises above baseline)
– Leading (difference between descent and ascent)

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.10 Font metrics

Xy1Õ
leading

height ascent

baseline
descent

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.11 FontMetrics and Graphics
methods for obtaining font metrics.

Method Description
public int getAscent() Returns a value representing the ascent of a font in points.
// FontMetrics class
public int getDescent() Returns a value representing the descent of a font in points.
// FontMetrics class
public int getLeading() Returns a value representing the leading of a font in points.
// FontMetrics class
public int getHeight() Returns a value representing the height of a font in points.
// FontMetrics class
public FontMetrics Returns the FontMetrics object for the current drawing Font.
getFontMetrics()
// Graphics class
public FontMetrics Returns the FontMetrics object for the specified Font argument.
getFontMetrics( Font f )
// Graphics class
Fig. 11.11 FontMetrics and Graphics methods for obtaining font metric s.

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.12: Metrics.java
// Demonstrating methods of class FontMetrics and
Outline
3 // class Graphics useful for obtaining font metrics.
4
5 // Java core packages Metrics.java
6 import java.awt.*;
7 import java.awt.event.*;
8 Line 29
9 // Java extension packages
10 import javax.swing.*;
11 Line 30
12 public class Metrics extends JFrame {
13 Lines 32-35
14 // set window's title bar String and dimensions
15 public Metrics()
16 {
17 super( "Demonstrating FontMetrics" );
18
19 setSize( 510, 210 );
20 setVisible( true );
21 }
22
23 // display font metrics
24 public void paint( Graphics g )
25 { Set font to SansSerif 12-point bold
26 // call superclass's paint method
27 super.paint( g );
28 Obtain FontMetrics
29 g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) );
30 FontMetrics metrics = g.getFontMetrics(); object for current font
31 g.drawString( "Current font: " + g.getFont(), 10, 40 );
32 g.drawString( "Ascent: " + metrics.getAscent(), 10, 55 ); Use FontMetrics to
33 g.drawString( "Descent: " + metrics.getDescent(), 10, 70 );
34 g.drawString( "Height: " + metrics.getHeight(), 10, 85 );
obtain ascent, descent,
35 g.drawString( "Leading: " + metrics.getLeading(), 10, 100); height and leading
 2002 Prentice Hall, Inc. All rights reserved.
36 Outline
37 Font font = new Font( "Serif", Font.ITALIC, 14 );
38 metrics = g.getFontMetrics( font );
Repeat same process for
39 g.setFont( font ); Serif 14-point italic font
40 g.drawString( "Current font: " + font, 10, 130 ); Metrics.java
41 g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 );
42 g.drawString( "Descent: " + metrics.getDescent(), 10, 160); Lines 37-44
43 g.drawString( "Height: " + metrics.getHeight(), 10, 175 );
44 g.drawString( "Leading: " + metrics.getLeading(), 10, 190);
45 }
46
47 // execute application
48 public static void main( String args[] )
49 {
50 Metrics application = new Metrics();
51
52 application.setDefaultCloseOperation(
53 JFrame.EXIT_ON_CLOSE );
54 }
55
56 } // end class Metrics

 2002 Prentice Hall, Inc. All rights reserved.


11.5 Drawing Lines, Rectangles and
Ovals
• Class Graphics
– Provides methods for drawing lines, rectangles and ovals
• All drawing methods require parameters width and height

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.13 Graphics methods that
draw lines, rectangle and ovals.

Method Description
public void drawLine( int x1, Draws a line between the point (x1, y1) and the point (x2, y2).
int y1, int x2, int y2 )
public void drawRect( int x, Draws a rectangle of the specified width and height. The top-
int y, int width, int height ) left corner of the rectangle has the coordinates (x, y).

public void fillRect( int x, Draws a solid rectangle with the specified width and height.
int y, int width, int height ) The top-left corner of the rectangle has the coordinate (x, y).

public void clearRect( int x, Draws a solid rectangle with the specified width and height in
int y, int width, int height ) the current background color. The top-left corner of the rectangle
has the coordinate (x, y).
public void drawRoundRect( int Draws a rectangle with rounded corners in the current color with the
x, int y, int width, int specified width and height. The arcWidth and arcHeight
height, int arcWidth, int
determine the rounding of the corners (see Fig. 11.15).
arcHeight )
public void fillRoundRect( int Draws a solid rectangle with rounded corners in the current color
x, int y, int width, int with the specified width and height. The arcWidth and
height, int arcWidth, int
arcHeight )
arcHeight determine the rounding of the corners (see Fig. 11.15).

Fig. 11.13 Graphics methods that draw lines, rec tangles and ovals (Part 1 of 2).

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.13 Graphics methods that
draw lines, rectangle and ovals (Part
2).

Method Description
public void fill3DRect( Draws a filled three-dimensional rectangle in the current color with the
int x, int y, int width, specified width and height. The top-left corner of the rectangle
int height, boolean b )
has the coordinates (x, y). The rectangle appears raised when b is true
and is lowered when b is false.
public void drawOval( int Draws an oval in the current color with the specified width and
x, int y, int width, int height. The bounding rectangle’s top-left corner is at the
height )
coordinates (x, y). The oval touches all four sides of the bounding
rectangle at the center of each side (see Fig. 11.16).
public void fillOval( int Draws a filled oval in the current color with the specified width and
x, int y, int width, int height. The bounding rectangle’s top-left corner is at the
height )
coordinates (x, y). The oval touches all four sides of the bounding
rectangle at the center of each side (see Fig. 11.16).
Fig. 11.13 Graphics methods that draw lines, rectangles and ovals (Part 2 o f 2).

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.14: LinesRectsOvals.java
// Drawing lines, rectangles and ovals
Outline
3
4 // Java core packages
5 import java.awt.*; LinesRectsOvals.
6 import java.awt.event.*; java
7
8 // Java extension packages
9 import javax.swing.*;
10
11 public class LinesRectsOvals extends JFrame {
12
13 // set window's title bar String and dimensions
14 public LinesRectsOvals()
15 {
16 super( "Drawing lines, rectangles and ovals" );
17
18 setSize( 400, 165 );
19 setVisible( true );
20 }
21
22 // display various lines, rectangles and ovals
23 public void paint( Graphics g )
24 {
25 // call superclass's paint method
26 super.paint( g );
27
28 g.setColor( Color.red );
29 g.drawLine( 5, 30, 350, 30 );
30
31 g.setColor( Color.blue );
32 g.drawRect( 5, 40, 90, 55 );
33 g.fillRect( 100, 40, 90, 55 );
34
35 g.setColor( Color.cyan );
 2002 Prentice Hall, Inc. All rights reserved.
36 g.fillRoundRect( 195, 40, 90, 55, 50, 50 ); Outline
Draw filled rounded rectangle
37 g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
38 Draw (non-filled) rounded rectangle
39 g.setColor( Color.yellow );
40 g.draw3DRect( 5, 100, 90, 55, true ); Draw 3D rectangleLinesRectsOvals.
41 g.fill3DRect( 100, 100, 90, 55, false ); java
42 Draw filled 3D rectangle
43 g.setColor( Color.magenta );
Line 36
44 g.drawOval( 195, 100, 90, 55 ); Draw oval
45 g.fillOval( 290, 100, 90, 55 );
46 } Line 37
Draw filled oval
47
48 // execute application
49 public static void main( String args[] ) Line 40
50 {
51 LinesRectsOvals application = new LinesRectsOvals();
52 Line 41
53 application.setDefaultCloseOperation(
54 JFrame.EXIT_ON_CLOSE ); Line 44
55 }
56
57 } // end class LinesRectsOvals Line 45

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.15 The arc width and height
for rounded rectangles.

(x, y)

arc height
a rc width
height

width

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.16 An oval bounded by a
rectangle.

(x, y)

height

wid th

 2002 Prentice Hall, Inc. All rights reserved.


11.6 Drawing Arcs

• Arc
– Portion of oval
– Measured in degrees
– Sweeps the number of degrees in arc angle
– Sweep starts at starting angle
• Counterclockwise sweep is measure in positive degrees
• Clockwise sweep is measure in negative degrees

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.17 Positive and negative arc
angles.

Positive angles Negative angles


90° 90°

180° 0° 180° 0°

270° 270°

 2002 Prentice Hall, Inc. All rights reserved.


11.18 Graphics methods for drawing
arcs.

Method Description
public void drawArc( int x, Draws an arc relative to the bounding rectangle’s top-left
int y, int width, int height, coordinates (x, y) with the specified width and height.
int startAngle, int arcAngle ) The arc segment is drawn starting at startAngle and sweeps
arcAngle degrees.
public void fillArc( int x, Draws a solid arc (i.e., a sector) relative to the bounding
int y, int width, int height, rectangle’s top-left coordinates (x, y) with the specified
int startAngle, int arcAngle ) width and height. The arc segment is drawn starting at
startAngle and sweeps arcAngle degrees.
Fig. 11.18 Graphics methods for drawing arcs.

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.19: DrawArcs.java
// Drawing arcs
Outline
3
4 // Java core packages
5 import java.awt.*; DrawArcs.java
6 import java.awt.event.*;
7 Lines 29-32
8 // Java extension packages
9 import javax.swing.*;
10
11 public class DrawArcs extends JFrame {
12
13 // set window's title bar String and dimensions
14 public DrawArcs()
15 {
16 super( "Drawing Arcs" );
17
18 setSize( 300, 170 );
19 setVisible( true );
20 }
21
22 // draw rectangles and arcs
23 public void paint( Graphics g )
24 {
25 // call superclass's paint method
26 super.paint( g );
27
28 // start at 0 and sweep 360 degrees Draw first arc that
29 g.setColor( Color.yellow );
30 g.drawRect( 15, 35, 80, 80 ); sweeps 360 degrees and
31 g.setColor( Color.black ); is contained in rectangle
32 g.drawArc( 15, 35, 80, 80, 0, 360 );
33
34 // start at 0 and sweep 110 degrees
35 g.setColor( Color.yellow );
 2002 Prentice Hall, Inc. All rights reserved.
36 g.drawRect( 100, 35, 80, 80 ); Draw second arc thatOutline
37 g.setColor( Color.black ); sweeps 110 degrees and
38 g.drawArc( 100, 35, 80, 80, 0, 110 );
39
is contained in rectangle
40 // start at 0 and sweep -270 degrees DrawArcs.java
41 g.setColor( Color.yellow );
42 Draw third arc that
g.drawRect( 185, 35, 80, 80 ); Lines 35-38
43 g.setColor( Color.black ); sweeps -270 degrees and
44 g.drawArc( 185, 35, 80, 80, 0, -270 ); is contained in rectangle
45 Lines 41-44
46 // start at 0 and sweep 360 degrees
47 g.fillArc( 15, 120, 80, 40, 0, 360 ); Draw fourth arc that is filled, has starting
48 Line360
angle 0 and sweeps 47 degrees
49 // start at 270 and sweep -90 degrees
50
51
g.fillArc( 100, 120, 80, 40, 270, -90 );
Draw fifth arc thatLine 50 has starting
is filled,
52 // start at 0 and sweep -270 degrees angle 270 and sweeps -90 degrees
53 g.fillArc( 185, 120, 80, 40, 0, -270 ); Line 53
54 } Draw sixth arc that is filled, has starting
55
56 // execute application
angle 0 and sweeps -270 degrees
57 public static void main( String args[] )
58 {
59 DrawArcs application = new DrawArcs();
60
61 application.setDefaultCloseOperation(
62 JFrame.EXIT_ON_CLOSE );
63 }
64
65 } // end class DrawArcs

 2002 Prentice Hall, Inc. All rights reserved.


Outline

DrawArcs.java.

Output

 2002 Prentice Hall, Inc. All rights reserved.


11.7 Drawing Polygons and
Polylines
• Class Polygon
– Polygons
• Multisided shapes
– Polylines
• Series of connected points

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.20 Graphics methods for
drawing polygons and class Polygon
constructors
Method Description
public void drawPolygon( int xPoints[], Draws a polygon. The x-coordinate of each point is specified in the xPoints
int yPoints[],int points ) array and the y-coordinate of each point is specified in the yPoints array. The
last argument specifies the number of points. This method draws a closed
polygon—even if the last point is different from the first point.
public void drawPolyline( Draws a series of connected lines. The x-coordinate of each point is specified in
int xPoints[], int yPoints[], the xPoints array and the y-coordinate of each point is specified in the
int points ) yPoints array. The last argument specifies the number of points. If the last
point is different from the first point, the polyline is not closed.
public void drawPolygon( Polygon p ) Draws the specified closed polygon.
public void fillPolygon( int xPoints[], Draws a solid polygon. The x-coordinate of each point is specified in the
int yPoints[], int points ) xPoints array and the y-coordinate of each point is specified in the yPoints
array. The last argument specifies the number of points. This method draws a
closed polygon—even if the last point is different from the first point.
public void fillPolygon( Polygon p ) Draws the specified solid polygon. The polygon is closed.
public Polygon() Constructs a new polygon object. The polygon does not contain any points.
// Polygon class
public Polygon( int xValues[], Constructs a new polygon object. The polygon has numberOfPoints sides,
int yValues[], int numberOfPoints ) with each point consisting of an x-coordinate from xValues and a y-coordinate
// Polygon class from yValues.
Fig. 11.20 Graphics methods for drawing polygons and class Polygon constructors.

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.21: DrawPolygons.java
// Drawing polygons
Outline
3
4 // Java core packages
5 import java.awt.*; DrawPolygons.java
6 import java.awt.event.*;
7 Lines 28-29
8 // Java extension packages
9 import javax.swing.*;
10 Line 32
11 public class DrawPolygons extends JFrame {
12
13 // set window's title bar String and dimensions Lines 34-35
14 public DrawPolygons()
15 {
16 super( "Drawing Polygons" );
17
18 setSize( 275, 230 );
19 setVisible( true );
20 }
21
22 // draw polygons and polylines int arrays specifying
23 public void paint( Graphics g )
24 {
Polygon polygon1 points
25 // call superclass's paint method
26 super.paint( g );
27 Draw polygon1 to screen
28 int xValues[] = { 20, 40, 50, 30, 20, 15 };
29 int yValues[] = { 50, 50, 60, 80, 80, 60 };
30 Polygon polygon1 = new Polygon( xValues, yValues, 6 ); int arrays specifying
31 Polygon polygon2 points
32 g.drawPolygon( polygon1 );
33
34 int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
35 int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };
 2002 Prentice Hall, Inc. All rights reserved.
36
37 g.drawPolyline( xValues2, yValues2, 7 );
Outline
Draw polygon2 to screen
38
39 int xValues3[] = { 120, 140, 150, 190 };
40
41
int yValues3[] = { 40, 70, 80, 60 };
Specify PolygonDrawPolygons.java
points and draw
42 g.fillPolygon( xValues3, yValues3, 4 ); (filled) polygon3 to screen
Line 37
43
44 Polygon polygon2 = new Polygon();
45 polygon2.addPoint( 165, 135 ); Lines 39-42
46 polygon2.addPoint( 175, 150 ); Method addPoint adds pairs
47 polygon2.addPoint( 270, 200 ); of x-y coordinates to Polygon
Lines 45-49
48 polygon2.addPoint( 200, 220 );
49 polygon2.addPoint( 130, 180 );
50
51 g.fillPolygon( polygon2 );
52 }
53
54 // execute application
55 public static void main( String args[] )
56 {
57 DrawPolygons application = new DrawPolygons();
58
59 application.setDefaultCloseOperation(
60 JFrame.EXIT_ON_CLOSE );
61 }
62
63 } // end class DrawPolygons

 2002 Prentice Hall, Inc. All rights reserved.


Outline

DrawPolygons.java

Output

 2002 Prentice Hall, Inc. All rights reserved.


11.8 Java 2D API

• Java 2D API
– Provides advanced 2D graphics capabilities
• java.awt
• java.awt.image
• java.awt.color
• java.awt.font.geom
• java.awt.print
• java.awt.image.renderable
– Uses class java.awt.Graphics2D
• Extends class java.awt.Graphics

 2002 Prentice Hall, Inc. All rights reserved.


11.9 Java 2D Shapes

• Java 2D shapes
– Package java.awt.geom
• Ellipse2D.Double
• Rectangle2D.Double
• RoundRectangle2D.Double
• Arc3D.Double
• Lines2D.Double

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.22: Shapes.java
// Demonstrating some Java2D shapes
Outline
3
4 // Java core packages
5 import java.awt.*; Shapes.java
6 import java.awt.event.*;
7 import java.awt.geom.*;
8 import java.awt.image.*; Lines 34-35
9
10 // Java extension packages
11 import javax.swing.*;
12
13 public class Shapes extends JFrame {
14
15 // set window's title bar String and dimensions
16 public Shapes()
17 {
18 super( "Drawing 2D shapes" );
19
20 setSize( 425, 160 );
21 setVisible( true );
22 }
23
24 // draw shapes with Java2D API
25 public void paint( Graphics g )
26 {
27 // call superclass's paint method
28 super.paint( g );
29 Use GradientPaint to
30 // create 2D by casting g to Graphics2D fill shape with gradient
31 Graphics2D g2d = ( Graphics2D ) g;
32
33 // draw 2D ellipse filled with a blue-yellow gradient
34 g2d.setPaint( new GradientPaint( 5, 30, Color.blue, 35,
35 100, Color.yellow, true ) );
 2002 Prentice Hall, Inc. All rights reserved.
36
37
g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
Outline
Fill ellipse with gradient
38 // draw 2D rectangle in red
39 g2d.setPaint( Color.red ); Use BasicStroke to draw
40 g2d.setStroke( new BasicStroke( 10.0f ) ); Shapes.java
2D red-border rectangle
41 g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) );
42
43 // draw 2D rounded rectangle with a buffered background Line 36
44 BufferedImage buffImage = new BufferedImage( BufferedImage produces
45 10, 10, BufferedImage.TYPE_INT_RGB );
46
image Lines 40-41
to be manipulated
47 Graphics2D gg = buffImage.createGraphics();
48 gg.setColor( Color.yellow ); // draw in yellow Lines 44-45
49 gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle
50 gg.setColor( Color.black ); // draw in black
51 gg.drawRect( 1, 1, 6, 6 ); // draw a rectangle Lines
Draw 47-55
texture into
52 gg.setColor( Color.blue ); // draw in blue BufferedImage
53 gg.fillRect( 1, 1, 3, 3 ); // draw a filled rectangle Lines 58-61
54 gg.setColor( Color.red ); // draw in red
55 gg.fillRect( 4, 4, 3, 3 ); // draw a filled rectangle
56 Lines 64-67
57 // paint buffImage onto the JFrame
58 g2d.setPaint( new TexturePaint(
59 buffImage, new Rectangle( 10, 10 ) ) ); Use BufferedImage as texture
60 g2d.fill( new RoundRectangle2D.Double(
61 155, 30, 75, 100, 50, 50 ) );
for painting rounded rectangle
62
63 // draw 2D pie-shaped arc in white
64 g2d.setPaint( Color.white );
65 g2d.setStroke( new BasicStroke( 6.0f ) );
66 g2d.draw( new Arc2D.Double(
Use Arc2D.PIE to
67 240, 30, 75, 100, 0, 270, Arc2D.PIE ) ); draw white-border
68 2D pie-shaped arc
69 // draw 2D lines in green and yellow
70 g2d.setPaint( Color.green );
 2002 Prentice Hall, Inc. All rights reserved.
71 g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) ); Outline
Draw solid green line
72
73 float dashes[] = { 10 };
74
75 g2d.setPaint( Color.yellow ); Shapes.java
76 g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND, Draw dashed yellow line
77 BasicStroke.JOIN_ROUND, 10, dashes, 0 ) ); Linesolid
71 green line
78 g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) ); that crosses
79 }
80 Lines 75-78
81 // execute application
82 public static void main( String args[] )
83 {
84 Shapes application = new Shapes();
85
86 application.setDefaultCloseOperation(
87 JFrame.EXIT_ON_CLOSE );
88 }
89
90 } // end class Shapes

 2002 Prentice Hall, Inc. All rights reserved.


1
2
// Fig. 11.23: Shapes2.java
// Demonstrating a general path
Outline
3
4 // Java core packages
5 import java.awt.*; Shapes2.java
6 import java.awt.event.*;
7 import java.awt.geom.*;
8 Lines 31-34
9 // Java extension packages
10 import javax.swing.*;
11
12 public class Shapes2 extends JFrame {
13
14 // set window's title bar String, background color
15 // and dimensions
16 public Shapes2()
17 {
18 super( "Drawing 2D Shapes" );
19
20 getContentPane().setBackground( Color.yellow );
21 setSize( 400, 400 );
22 setVisible( true );
23 }
24
25 // draw general paths
26 public void paint( Graphics g )
27 {
28 // call superclass's paint method
29 super.paint( g );
30
31 int xPoints[] =
32 { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
33 int yPoints[] =
x-y coordinates that comprise star
34 { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
35
 2002 Prentice Hall, Inc. All rights reserved.
36
37
Graphics2D g2d = ( Graphics2D ) g; GeneralPath is a shape Outline
38 // create a star from a series of points constructed from straight
39 GeneralPath star = new GeneralPath(); lines and complex curves
40 Shapes2.java
41 // set the initial coordinate of the General Path
42 star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
43 Line 39
44 // create the star--this does not draw the star
45 for ( int count = 1; count < xPoints.length; count++ ) Create
Lines star
42-49
46 star.lineTo( xPoints[ count ], yPoints[ count ] );
47
48 // close the shape Lines 55-67
49 star.closePath();
50
51 // translate the origin to (200, 200)
52 g2d.translate( 200, 200 );
53
54 // rotate around origin and draw stars in random colors
55 for ( int count = 1; count <= 20; count++ ) {
56
57 // rotate coordinate system
58 g2d.rotate( Math.PI / 10.0 );
59
60 // set random drawing color
61 g2d.setColor( new Color(
Draw filled, randomly colored
62 ( int ) ( Math.random() * 256 ), star 20 times around origin
63 ( int ) ( Math.random() * 256 ),
64 ( int ) ( Math.random() * 256 ) ) );
65
66 // draw filled star
67 g2d.fill( star );
68 }
69
70 } // end method paint
 2002 Prentice Hall, Inc. All rights reserved.
71 Outline
72 // execute application
73 public static void main( String args[] )
74 {
75 Shapes2 application = new Shapes2(); Shapes2.java
76
77 application.setDefaultCloseOperation(
78 JFrame.EXIT_ON_CLOSE );
79 }
80
81 } // end class Shapes2

 2002 Prentice Hall, Inc. All rights reserved.


11.10 (Optional Case Study)
Thinking About Objects: Designing
Interfaces With the UML
• Use UML to represent listener interfaces
– Class diagram modeling realizations
• Classes realize, or implement, interface behaviors
• Person realizes DoorListener
• In Java, class Person implements interface DoorListener

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.25 Class diagram that
models class Person realizing
interface DoorListener.

Perso n «inte rfa ce»


DoorListener
- ID : Integer
- mo ving : Boo lea n = true
- lo cation : Loca tion + doo rOpe ne d( Doo rEvent : do orEvent ) : vo id
+ d oorOpened ( ) : void + do orC lo sed( Do orEvent : d oorEve nt ) : void

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.26 Elided class diagram that
models class Person realizing
interface DoorListener

Perso n
DoorListener
- ID : Integer
- mo ving : Boo lea n = true
- lo cation : Loca tion
+ d oorOpened ( ) : void

 2002 Prentice Hall, Inc. All rights reserved.


1 // Person.java Outline
2 // Generated from Fig. 11.24
3 public class Person implements DoorListener {
4
5 // attributes Person.java
6 private int ID;
7 private boolean moving = true; Lines 3 and 14-15
8 private Location location;
9
10 // constructor Class Person must implement
11 public Person() {} DoorListener methods
12
13 // methods of DoorListener
14 public void doorOpened( DoorEvent doorEvent ) {}
15 public void doorClosed( DoorEvent doorEvent ) {}
16 }

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.27 Class diagram that
models realizations in the elevator
model.
PersonMoveListener ButtonListener DoorListener BellListener

ElevatorModel Elevator

LightListener ButtonListener DoorListener DoorListener

ElevatorShaft Person

ElevatorMoveListener

Door Light Bell Button

 2002 Prentice Hall, Inc. All rights reserved.


Fig. 11.28 Class diagram for listener
interfaces
«interfa ce»
Be llListener

+ b ellRang ( BellEvent : be llEvent ) : void

«interface»
ButtonListener

+ b uttonPresse d( ButtonEvent : b uttonEvent ) : void


+ b uttonReset( ButtonEvent : b uttonEvent ) : void

«inte rface»
DoorListener

+ doo rOpe ne d( Doo rEvent : do orEvent ) : vo id


+ do orC lo sed( Do orEvent : d oorEve nt ) : void

«interfa ce»
ElevatorM oveListener

+ eleva to rArrived ( Eleva to rMo veEvent : e levatorMoveEvent ) : void


+ eleva to rDep arted ( ElevatorM ove Eve nt : eleva to rMo veEvent ) : void

«inte rface»
LightListener

+ lightTurne dOn( Lig htEvent : lig htEvent ) : vo id


+ lightTurne dOff( Lig htEvent : lig htEvent ) : vo id

«interfac e»
Perso nMoveListener

+ personC rea te d( PersonMoveEvent : p ersonM ove Event ) : vo id


+ personArrived ( Pe rsonM oveEvent : personMoveEvent ) : void
+ personDep arted ( PersonMoveEvent : pe rsonM oveEvent ) : void
+ personPresse dButton( PersonMoveEvent : personMo veEvent ) : vo id
+ personEntered( PersonMo veEvent : p erso nMoveEve nt ) : void
+ personExited( PersonMoveEvent : p erso nMoveEve nt ) : vo id

 2002 Prentice Hall, Inc. All rights reserved.

You might also like