Transcript Document

Chapter 12 - Graphics and Java 2D
Outline
12.1
Introduction
12.2
Graphics Contexts and Graphics Objects
12.3
Color Control
12.4
Font Control
12.5
Drawing Lines, Rectangles and Ovals
12.6
Drawing Arcs
12.7
Drawing Polygons and Polylines
12.8
Java2D API
12.9
(Optional Case Study) Thinking About Objects: Designing
Interfaces with the UML
 2003 Prentice Hall, Inc. All rights reserved.
12.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
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.1 Classes and interfaces used in this chapter from Java’s original
graphics capabilities and from the Java2D API. [Note: Class Object appears
here because it is the superclass of the Java class hierarchy.]
Object
Color
Component
Font
FontMetrics
Graphics
Polygon
Classes and interfaces from the Java2D API that appear
in package java.awt
Graphics2D
interface
java.awt.Paint
BasicStroke
interface
java.awt.Shape
GradientPaint
interface
java.awt.Stroke
TexturePaint
Classes from the Java2D API that appear in package
java.awt.geom
GeneralPath
Line2D
RectangularShape
Arc2D
Ellipse2D
Rectangle2D
RoundRectangle2D
 2003 Prentice Hall, Inc. All rights reserved.
12.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
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.2 Java coordinate system. Units are
measured in pixels
+x
(0, 0)
X a xis
(x , y )
+y
Y a xis
 2003 Prentice Hall, Inc. All rights reserved.
12.2 Graphics Contexts 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
 2003 Prentice Hall, Inc. All rights reserved.
12.3 Color Control
• Class Color
– Defines methods and constants for manipulating colors
– Colors are created from red, green and blue components
• RGB values
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.3 Color constants and their RGB
values
Color constant
public final static Color ORANGE
Color
RGB value
public final static Color PINK
orange
pink
255, 200, 0
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 LIGHT_GRAY
light gray
192, 192, 192
public final static Color DARK_GRAY
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
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.4 Color methods and color-related
Graphics methods
Method
Description
Color constructors and methods
public Color( int r, int g, int b )
Creates a color based on red, green and blue components expressed as integers
from 0 to 255.
public Color( float r, float g, float b )
Creates a color based on red, green and blue components expressed as
floating-point values from 0.0 to 1.0.
public int getRed()
Returns a value between 0 and 255 representing the red content.
public int getGreen()
Returns a value between 0 and 255 representing the green content.
public int getBlue()
Returns a value between 0 and 255 representing the blue content.
Graphics methods for manipulating Colors
public Color getColor()
Returns a Color object representing the current color for the graphics
context.
public void setColor( Color c )
Sets the current color for drawing with the graphics context.
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Outline
// Fig. 12.5: ShowColors.java
// Demonstrating Colors.
import java.awt.*;
import javax.swing.*;
ShowColors.java
public class ShowColors extends JFrame {
Line 18
// constructor sets window's title bar string and dimensions
public ShowColors()
{
super( "Using colors" );
setSize( 400, 130 );
setVisible( true );
Paint window when
application begins
execution
Line 24
Line 25
Line 26
}
// draw rectangles and Strings in different colors
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
Method setColor
sets color’s RGB value
Method fillRect creates filled
rectangle at specified coordinates
using current RGB value
// set new drawing color using integers
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );
Method drawString draws
colored text at specified coordinates
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );
// set new drawing color using static Color objects
g.setColor( Color.BLUE );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );
// display individual RGB values
Color color = Color.MAGENTA;
g.setColor( color );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + color.getRed() + ", " +
color.getGreen() + ", " + color.getBlue(), 130, 115 );
Outline
ShowColors.java
Lines 34-39
Use constant in class Color
to specify current color
} // end method paint
// execute application
public static void main( String args[] )
{
ShowColors application = new ShowColors();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class ShowColors
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Fig. 12.6: ShowColors2.java
// Choosing colors with JColorChooser.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Outline
ShowColors2.jav
a
public class ShowColors2 extends JFrame {
private JButton changeColorButton;
private Color color = Color.LIGHT_GRAY;
private Container container;
// set up GUI
public ShowColors2()
{
super( "Using JColorChooser" );
container = getContentPane();
container.setLayout( new FlowLayout() );
// set up changeColorButton and register its event handler
changeColorButton = new JButton( "Change Color" );
changeColorButton.addActionListener(
 2003 Prentice Hall, Inc.
All rights reserved.
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
new ActionListener() {
// anonymous inner class
// display JColorChooser when user clicks button
public void actionPerformed( ActionEvent event )
{
color = JColorChooser.showDialog(
ShowColors2.this, "Choose a color", color );
// set default color, if no color is returned
if ( color == null )
color = Color.LIGHT_GRAY;
Outline
JColorChooser allows
user to chooseShowColors2.jav
from among
severalacolors
Line 29
static method
Line displays
29
showDialog
the color chooser dialog
// change content pane's background color
container.setBackground( color );
}
} // end anonymous inner class
); // end call to addActionListener
container.add( changeColorButton );
setSize( 400, 130 );
setVisible( true );
} // end ShowColor2 constructor
 2003 Prentice Hall, Inc.
All rights reserved.
51
52
53
54
55
56
57
58
// execute application
public static void main( String args[] )
{
ShowColors2 application = new ShowColors2();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
ShowColors2.jav
a
} // end class ShowColors2
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
ShowColors2.jav
a
 2003 Prentice Hall, Inc.
All rights reserved.
Fig. 12.7 HSB and RGB tabs of the
JColorChooser dialog
 2003 Prentice Hall, Inc. All rights reserved.
12.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)
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.8 Font-related methods and constants
Method or constant
Description
Font constants, constructors and methods for drawing polygons
public final static int PLAIN
A constant representing a plain font style.
public final static int BOLD
A constant representing a bold font style.
public final static int ITALIC
A constant representing an italic font style.
public Font( String name, int style, int size )
Creates a Font object with the specified font, style and size.
public int getStyle()
Returns an integer value indicating the current font style.
public int getSize()
Returns an integer value indicating the current font size.
public String getName()
Returns the current font name as a string.
public String getFamily()
Returns the font’s family name as a string.
public boolean isPlain()
Tests a font for a plain font style. Returns true if the font is plain.
public boolean isBold()
Tests a font for a bold font style. Returns true if the font is bold.
public boolean isItalic()
Tests a font for an italic font style. Returns true if the font is italic.
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.8 Font-related methods and constants
Method or constant
Description
Graphics methods for manipulating Fonts
public Font getFont()
Returns a Font object reference representing the current font.
public void setFont( Font f )
Sets the current font to the font, style and size specified by the Font
object reference f.
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
// Fig. 12.9: Fonts.java
// Using fonts.
import java.awt.*;
import javax.swing.*;
Fonts.java
public class Fonts extends JFrame {
Line 24
// set window's title bar and dimensions
public Fonts()
{
super( "Using fonts" );
Line 25
setSize( 420, 125 );
setVisible( true );
}
// display Strings in different fonts and colors
public void paint( Graphics g )
{
// call superclass's paint method
super.paint( g );
Method setFont sets current font
// set font to Serif (Times), bold, 12pt and draw a string
g.setFont( new Font( "Serif", Font.BOLD, 12 ) );
g.drawString( "Serif 12 point bold.", 20, 50 );
Draw text using current font
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// set font to Monospaced (Courier), italic, 24pt and draw a string
g.setFont( new Font( "Monospaced", Font.ITALIC, 24 ) );
g.drawString( "Monospaced 24 point italic.", 20, 70 );
// set font to SansSerif (Helvetica), plain, 14pt and draw a string
g.setFont( new Font( "SansSerif", Font.PLAIN, 14 ) );
g.drawString( "SansSerif 14 point plain.", 20, 90 );
Outline
Fonts.java
Line 32
Line 37
14-point plain
// set font to Serif (Times), bold/italic, 18pt and draw Set
a string
font to SansSerif
g.setColor( Color.RED );
g.setFont( new Font( "Serif", Font.BOLD + Font.ITALIC, 18 ) );
g.drawString( g.getFont().getName() + " " + g.getFont().getSize() +
" point bold italic.", 20, 110 );
Set font to Serif 18-point bold italic
} // end method paint
// execute application
public static void main( String args[] )
{
Fonts application = new Fonts();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class Fonts
 2003 Prentice Hall, Inc.
All rights reserved.
12.4 Font Control
• Font metrics
–
–
–
–
Height
Descent (amount character dips below baseline)
Ascent (amount character rises above baseline)
Leading (difference between descent and ascent)
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.10 Font metrics
he ight
Xy1Õ
 2003 Prentice Hall, Inc. All rights reserved.
le ading
asc e nt
ba seline
desc ent
Fig. 12.11 FontMetrics and Graphics
methods for obtaining font metrics
Method
Description
FontMetrics methods
public int getAscent()
Returns a value representing the ascent of a font in points.
public int getDescent()
Returns a value representing the descent of a font in points.
public int getLeading()
Returns a value representing the leading of a font in points.
public int getHeight()
Returns a value representing the height of a font in points.
Graphics methods for getting a Font’s FontMetrics
public FontMetrics getFontMetrics()
Returns the FontMetrics object for the current drawing Font.
public FontMetrics getFontMetrics( Font f )
Returns the FontMetrics object for the specified Font argument.
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Fig. 12.12: Metrics.java
// FontMetrics and Graphics methods useful for obtaining font metrics.
import java.awt.*;
import javax.swing.*;
public class Metrics extends JFrame {
// set window's title bar String and dimensions
public Metrics()
{
super( "Demonstrating FontMetrics" );
Outline
Metrics.java
Line 22
Line 23
setSize( 510, 210 );
setVisible( true );
}
// display font metrics
public void paint( Graphics g )
Set
{
super.paint( g ); // call superclass's paint method
g.setFont( new Font( "SansSerif", Font.BOLD, 12 ) );
FontMetrics metrics = g.getFontMetrics();
g.drawString( "Current font: " + g.getFont(), 10, 40 );
font to SansSerif 12-point bold
Obtain FontMetrics
object for current font
 2003 Prentice Hall, Inc.
All rights reserved.
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
g.drawString(
g.drawString(
g.drawString(
g.drawString(
"Ascent: " + metrics.getAscent(), 10, 55 );
"Descent: " + metrics.getDescent(), 10, 70 );
"Height: " + metrics.getHeight(), 10, 85 );
"Leading: " + metrics.getLeading(), 10, 100 );
Font font = new Font( "Serif", Font.ITALIC, 14 );
metrics = g.getFontMetrics( font );
g.setFont( font );
g.drawString( "Current font: " + font, 10, 130 );
g.drawString( "Ascent: " + metrics.getAscent(), 10, 145 );
g.drawString( "Descent: " + metrics.getDescent(), 10, 160 );
g.drawString( "Height: " + metrics.getHeight(), 10, 175 );
g.drawString( "Leading: " + metrics.getLeading(), 10, 190 );
Outline
Use FontMetrics
to
obtain ascent, descent,
height and leading
Metrics.java
Repeat same process for
Lines 25-28
Serif 14-point italic font
Lines 30-37
} // end method paint
// execute application
public static void main( String args[] )
{
Metrics application = new Metrics();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class Metrics
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
Metrics.java
 2003 Prentice Hall, Inc.
All rights reserved.
12.5 Drawing Lines, Rectangles and Ovals
• Class Graphics
– Provides methods for drawing lines, rectangles and ovals
• All drawing methods require parameters width and height
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.13 Graphics methods that draw lines,
rectangles and ovals
Method
Description
public void drawLine( int x1, int y1, int x2, int y2 )
Draws a line between the point (x1, y1) and the point (x2, y2).
public void drawRect( int x, int y, int width, int height )
Draws a rectangle of the specified width and height. The top-left corner of
the rectangle has the coordinates (x, y).
public void fillRect( int x, int y, int width, int height )
Draws a solid rectangle with the specified width and height. The top-left
corner of the rectangle has the coordinate (x, y).
public void clearRect( int x, int y, int width, int height )
Draws a solid rectangle with the specified width and height in the current
background color. The top-left corner of the rectangle has the coordinate (x, y).
public void drawRoundRect( int x, int y, int width, int height,
int arcWidth, int arcHeight )
Draws a rectangle with rounded corners in the current color with the specified
width and height. The arcWidth and arcHeight determine the rounding of
the corners (see Fig. 12.15).
public void fillRoundRect( int x, int y, int width, int height,
int arcWidth, int arcHeight )
Draws a solid rectangle with rounded corners in the current color with the
specified width and height. The arcWidth and arcHeight determine the
rounding of the corners (see Fig. 12.15).
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.13 Graphics methods that draw lines,
rectangles and ovals
Method
Description
public void draw3DRect( int x, int y, int width, int height, boolean b )
Draws a three-dimensional rectangle in the current color with the specified
width and height. The top-left corner of the rectangle has the coordinates ( x,
y). The rectangle appears raised when b is true and lowered when b is false.
public void fill3DRect( int x, int y, int width, int height, boolean b )
Draws a filled three-dimensional rectangle in the current color with the
specified width and height. The top-left corner of the rectangle has the
coordinates (x, y). The rectangle appears raised when b is true and lowered
when b is false.
public void drawOval( int x, int y, int width, int height )
Draws an oval in the current color with the specified width and height. The
bounding rectangle’s top-left corner is at the coordinates (x, y). The oval
touches all four sides of the bounding rectangle at the center of each side (see
Fig. 12.16).
public void fillOval( int x, int y, int width, int height )
Draws a filled oval in the current color with the specified width and height.
The bounding rectangle’s top-left corner is at the coordinates (x, y). The oval
touches all four sides of the bounding rectangle at the center of each side (see
Fig. 12.16).
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 12.14: LinesRectsOvals.java
// Drawing lines, rectangles and ovals.
import java.awt.*;
import javax.swing.*;
public class LinesRectsOvals extends JFrame {
Outline
LinesRectsOvals
.java
// set window's title bar String and dimensions
public LinesRectsOvals()
{
super( "Drawing lines, rectangles and ovals" );
setSize( 400, 165 );
setVisible( true );
}
// display various lines, rectangles and ovals
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
g.setColor( Color.RED );
g.drawLine( 5, 30, 350, 30 );
g.setColor( Color.BLUE );
g.drawRect( 5, 40, 90, 55 );
g.fillRect( 100, 40, 90, 55 );
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
g.setColor( Color.CYAN );
g.fillRoundRect( 195, 40, 90, 55, 50, 50 );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
g.setColor( Color.YELLOW );
g.draw3DRect( 5, 100, 90, 55, true );
g.fill3DRect( 100, 100, 90, 55, false );
g.setColor( Color.MAGENTA );
g.drawOval( 195, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );
} // end method paint
Outline
Draw filled rounded rectangle
LinesRectsOvals
Draw (non-filled) rounded .java
rectangle
Draw 3D rectangle
Line 30
Draw filled 3D rectangle
Line 31
Draw oval
Draw filled oval Line 34
// execute application
public static void main( String args[] )
{
LinesRectsOvals application = new LinesRectsOvals();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Line 35
Line 38
Line 39
} // end class LinesRectsOvals
 2003 Prentice Hall, Inc.
All rights reserved.
Fig. 12.15 Arc width and arc height for rounded
rectangles
( x, y)
arc height
a rc width
w idth
 2003 Prentice Hall, Inc. All rights reserved.
height
Fig. 12.16 Oval bounded by a rectangle
( x , y)
height
w id th
 2003 Prentice Hall, Inc. All rights reserved.
12.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
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.17 Positive and negative arc angles
Positive angles
Negative angles
90°
180°
90°
0°
270°
 2003 Prentice Hall, Inc. All rights reserved.
180°
0°
270°
Fig. 12.18 Graphics methods for drawing
arcs
Method
Description
public void drawArc( int x, int y, int width, int height, int startAngle,
int arcAngle )
Draws an arc relative to the bounding rectangle’s top-left coordinates (x, y)
with the specified width and height. The arc segment is drawn starting at
startAngle and sweeps arcAngle degrees.
public void fillArc( int x, int y, int width, int height, int startAngle,
int arcAngle )
Draws a solid arc (i.e., a sector) relative to the bounding rectangle’s top-left
coordinates (x, y) with the specified width and height. The arc segment is
drawn starting at startAngle and sweeps arcAngle degrees.
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Fig. 12.19: DrawArcs.java
// Drawing arcs.
import java.awt.*;
import javax.swing.*;
public class DrawArcs extends JFrame {
Outline
DrawArcs.java
Lines 24-26
// set window's title bar String and dimensions
public DrawArcs()
{
super( "Drawing Arcs" );
setSize( 300, 170 );
setVisible( true );
}
// draw rectangles and arcs
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
// start at 0 and sweep 360 degrees
g.setColor( Color.YELLOW );
g.drawRect( 15, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 15, 35, 80, 80, 0, 360 );
Draw first arc that
sweeps 360 degrees and
is contained in rectangle
 2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// start at 0 and sweep 110 degrees
g.setColor( Color.YELLOW );
g.drawRect( 100, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 100, 35, 80, 80, 0, 110 );
// start at 0 and sweep -270 degrees
g.setColor( Color.YELLOW );
g.drawRect( 185, 35, 80, 80 );
g.setColor( Color.BLACK );
g.drawArc( 185, 35, 80, 80, 0, -270 );
// start at 0 and sweep 360 degrees
g.fillArc( 15, 120, 80, 40, 0, 360 );
// start at 270 and sweep -90 degrees
g.fillArc( 100, 120, 80, 40, 270, -90 );
// start at 0 and sweep -270 degrees
g.fillArc( 185, 120, 80, 40, 0, -270 );
} // end method paint
Outline
Draw second arc that
DrawArcs.java
sweeps 110 degrees and
is contained in rectangle
Lines 30-32
Lines 36-38
Draw third arc that
sweeps -270 degrees
and41
Line
is contained in rectangle
Line 44
Draw fourth arc that is filled, has starting
angle 0 and sweeps 360
degrees
Line
47
Draw fifth arc that is filled, has starting
angle 270 and sweeps -90 degrees
Draw sixth arc that is filled, has starting
angle 0 and sweeps -270 degrees
 2003 Prentice Hall, Inc.
All rights reserved.
51
52
53
54
55
56
57
58
// execute application
public static void main( String args[] )
{
DrawArcs application = new DrawArcs();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
DrawArcs.java
} // end class DrawArcs
 2003 Prentice Hall, Inc.
All rights reserved.
12.7 Drawing Polygons and Polylines
• Class Polygon
– Polygons
• Multisided shapes
– Polylines
• Series of connected points
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.20 Graphics methods for drawing
polygons and class Polygon methods
Method
Description
Graphics methods for drawing polygons
public void drawPolygon( int xPoints[], int yPoints[], int points )
Draws a polygon. The x-coordinate of each point is specified in the 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. If the last point is different from the first point, the polygon is closed
by a line that connects the last point to the first point.
public void drawPolyline( int xPoints[], int yPoints[], int points )
Draws a sequence of connected lines. The x-coordinate of each point is
specified in the xPoints array and the y-coordinate of each point is specified in
the 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 polygon.
public void fillPolygon( int xPoints[], int yPoints[], int points )
Draws a solid polygon. The x-coordinate of each point is specified in the
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. If the last point is different from the first point, the polygon is
closed by a line that connects the last point to the first point.
public void fillPolygon( Polygon p )
Draws the specified solid polygon. The polygon is closed.
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.20 Graphics methods for drawing
polygons and class Polygon methods
Method
Description
Polygon constructors and methods
public Polygon()
Constructs a new polygon object. The polygon does not contain any points.
public Polygon( int xValues[], int yValues[], int numberOfPoints )
Constructs a new polygon object. The polygon has numberOfPoints sides,
with each point consisting of an x-coordinate from xValues and a y-coordinate
from yValues.
public void addPoint( int x, int y )
Adds pairs of x- and y-coordinates to the Polygon.
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 12.21: DrawPolygons.java
// Drawing polygons.
import java.awt.*;
import javax.swing.*;
public class DrawPolygons extends JFrame {
// set window's title bar String and dimensions
public DrawPolygons()
{
super( "Drawing Polygons" );
Outline
DrawPolygons.ja
va
Lines 22-23
Line 26
setSize( 275, 230 );
setVisible( true );
}
// draw polygons and polylines
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
int xValues[] = { 20, 40, 50, 30, 20, 15 };
int yValues[] = { 50, 50, 60, 80, 80, 60 };
Polygon polygon1 = new Polygon( xValues, yValues, 6 );
int arrays specifying
Polygon polygon1 points
Draw polygon1 to screen
g.drawPolygon( polygon1 );
 2003 Prentice Hall, Inc.
All rights reserved.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };
g.drawPolyline( xValues2, yValues2, 7 );
int xValues3[] = { 120, 140, 150, 190 };
int yValues3[] = { 40, 70, 80, 60 };
g.fillPolygon( xValues3, yValues3, 4 );
Polygon polygon2 =
polygon2.addPoint(
polygon2.addPoint(
polygon2.addPoint(
polygon2.addPoint(
polygon2.addPoint(
new Polygon();
165, 135 );
175, 150 );
270, 200 );
200, 220 );
130, 180 );
Outline
int arrays specifying
Polyline
points
DrawPolygons.ja
va
Draw Polyline to screen
Lines 28-29
Specify points and draw (filled)
Line
31
Polygon to
screen
Lines 33-36
Method addPoint adds pairs of
x-y coordinates to a Polygon
Line 39
g.fillPolygon( polygon2 );
} // end method paint
// execute application
public static void main( String args[] )
{
DrawPolygons application = new DrawPolygons();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class DrawPolygons
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
DrawPolygons.ja
va
 2003 Prentice Hall, Inc.
All rights reserved.
12.8 Java2D API
• Java 2D API
– Provides advanced 2D graphics capabilities
• java.awt
• java.awt.image
• java.awt.color
• java.awt.font
• java.awt.geom
• java.awt.print
• java.awt.image.renderable
– Uses class java.awt.Graphics2D
• Extends class java.awt.Graphics
 2003 Prentice Hall, Inc. All rights reserved.
12.8 Java2D API
• Java 2D shapes
– Package java.awt.geom
• Ellipse2D.Double
• Rectangle2D.Double
• RoundRectangle2D.Double
• Arc3D.Double
• Lines2D.Double
 2003 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Outline
// Fig. 12.22: Shapes.java
// Demonstrating some Java2D shapes.
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
Shapes.java
public class Shapes extends JFrame {
// set window's title bar String and dimensions
public Shapes()
{
super( "Drawing 2D shapes" );
setSize( 425, 160 );
setVisible( true );
}
// draw shapes with Java2D API
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
Graphics2D g2d = ( Graphics2D ) g;
// cast g to Graphics2D
 2003 Prentice Hall, Inc.
All rights reserved.
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
Outline
// draw 2D ellipse filled with a blue-yellow gradient
g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100,Use GradientPaint to
fill shape with gradient
Color.YELLOW, true ) );
g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
Shapes.java
// draw 2D rectangle in red
g2d.setPaint( Color.RED );
g2d.setStroke( new BasicStroke( 10.0f ) );
g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) );
// draw 2D rounded rectangle with a buffered background
BufferedImage buffImage = new BufferedImage( 10, 10,
BufferedImage.TYPE_INT_RGB );
Graphics2D gg = buffImage.createGraphics();
gg.setColor( Color.YELLOW ); // draw in yellow
gg.fillRect( 0, 0, 10, 10 ); // draw a filled rectangle
gg.setColor( Color.BLACK ); // draw in black
gg.drawRect( 1, 1, 6, 6 );
// draw a rectangle
gg.setColor( Color.BLUE );
// draw in blue
gg.fillRect( 1, 1, 3, 3 );
// draw a filled rectangle
gg.setColor( Color.RED );
// draw in red
gg.fillRect( 4, 4, 3, 3 );
// draw a filled rectangle
Fill ellipse with gradient
Lines 27-28
Use BasicStroke to draw
2D red-border rectangle
Line 29
Lines 33-34
BufferedImage produces
image to be manipulated
Lines 37-28
Lines 40-48
Draw texture into
BufferedImage
 2003 Prentice Hall, Inc.
All rights reserved.
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
Outline
// paint buffImage onto the JFrame
Use BufferedImage as texture
g2d.setPaint( new TexturePaint( buffImage,
for painting rounded rectangle
new Rectangle( 10, 10 ) ) );
g2d.fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );
Shapes.java
// draw 2D pie-shaped arc in white
g2d.setPaint( Color.WHITE );
g2d.setStroke( new BasicStroke( 6.0f ) );
g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
// draw 2D lines in green and yellow
g2d.setPaint( Color.GREEN );
g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );
Use Arc2D.PIE to
drawLines
white-border
51-52
2D pie-shaped arc
Line 58
Line 62
Draw solid green line
Line 69
float dashes[] = { 10 };
g2d.setPaint( Color.YELLOW );
g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_ROUND, 10, dashes, 0 ) );
g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
Draw dashed yellow line
that crosses solid green line
} // end method paint
 2003 Prentice Hall, Inc.
All rights reserved.
73
74
75
76
77
78
79
80
// execute application
public static void main( String args[] )
{
Shapes application = new Shapes();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
Outline
Shapes.java
} // end class Shapes
 2003 Prentice Hall, Inc.
All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Outline
// Fig. 12.23: Shapes2.java
// Demonstrating a general path.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
Shapes2.java
Lines 24-25
public class Shapes2 extends JFrame {
// set window's title bar String, background color and dimensions
public Shapes2()
{
super( "Drawing 2D Shapes" );
getContentPane().setBackground( Color.WHITE );
setSize( 400, 400 );
setVisible( true );
}
// draw general paths
public void paint( Graphics g )
{
super.paint( g ); // call superclass's paint method
x-y coordinates that comprise star
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
 2003 Prentice Hall, Inc.
All rights reserved.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath();
// create GeneralPath
// set the initial coordinate of the General Path
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
GeneralPath is a shape
Outline
constructed from straight
object
lines and complex curves
Shapes2.java
Line 28
Create star
Lines 31-37
// create the star--this does not draw the star
for ( int count = 1; count < xPoints.length; count++ )
star.lineTo( xPoints[ count ], yPoints[ count ] );
star.closePath();
// close the shape
g2d.translate( 200, 200 );
Lines 42-50
// translate the origin to (200, 200)
// rotate around origin and draw stars in random colors
for ( int count = 1; count <= 20; count++ ) {
g2d.rotate( Math.PI / 10.0 ); // rotate coordinate system
// set random drawing color
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star );
// draw filled star
Draw filled, randomly colored
star 20 times around origin
}
 2003 Prentice Hall, Inc.
All rights reserved.
Outline
Shapes2.java
 2003 Prentice Hall, Inc.
All rights reserved.
12.9 (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
 2003 Prentice Hall, Inc. All rights reserved.
Fig. 12.24 Class diagram that models class
Person realizing interface DoorListener
Person
- ID : Integer
- moving : Boolean = true
- location : Location
+ doorOpened( ) : void
+ doorClosed( ) : void
 2003 Prentice Hall, Inc. All rights reserved.
JavaInterface
DoorListener
+ doorOpened( doorEvent : DoorEvent ) : void
+ doorClosed( doorEvent : DoorEvent ) : void
Fig. 12.25 Elided class diagram that models class
Person realizing interface DoorListener
Person
- ID : Integer
- moving : Boolean = true
- location : Location
+ doorOpened( ) : void
+ doorClosed( ) : void
 2003 Prentice Hall, Inc. All rights reserved.
DoorListener
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Person.java
// Generated from Fig. 11.24
public class Person implements DoorListener {
// attributes
private int ID;
private boolean moving = true;
private Location location;
// constructor
public Person() {}
Outline
Person.java
Lines 3-15
Class Person must implement
DoorListener methods
// methods of DoorListener
public void doorOpened( DoorEvent doorEvent ) {}
public void doorClosed( DoorEvent doorEvent ) {}
}
 2003 Prentice Hall, Inc.
All rights reserved.
Fig. 12.27 Class diagram that models
realizations in the elevator model
ButtonListener
DoorListener
BellListener
Elevator
LightListener
ButtonListener
DoorListener
ElevatorShaft
DoorListener
Person
ElevatorMoveListener
Door
 2003 Prentice Hall, Inc. All rights reserved.
Light
Bell
Button
Fig. 12.28 Class diagram for listener interfaces
JavaInterface
BellListener
+ bellRang( BellEvent : bellEvent ) : void
JavaInterface
ButtonListener
+ buttonPressed( ButtonEvent : buttonEvent ) : void
+ buttonReset( ButtonEvent : buttonEvent ) : void
JavaInterface
DoorListener
+ doorOpened( DoorEvent : doorEvent ) : void
+ doorClosed( DoorEvent : doorEvent ) : void
JavaInterface
ElevatorMoveListener
+ elevatorArrived( ElevatorMoveEvent : elevatorMoveEvent ) : void
+ elevatorDeparted( ElevatorMoveEvent : elevatorMoveEvent ) : void
JavaInterface
LightListener
+ lightTurnedOn( LightEvent : lightEvent ) : void
+ lightTurnedOff( LightEvent : lightEvent ) : void
JavaInterface
PersonMoveListener
+ personCreated( PersonMoveEvent : personMoveEvent ) : void
+ personArrived( PersonMoveEvent : personMoveEvent ) : void
+ personDeparted( PersonMoveEvent : personMoveEvent ) : void
+ personPressedButton( PersonMoveEvent : personMoveEvent ) : void
+ personEntered( PersonMoveEvent : personMoveEvent ) : void
+ personExited( PersonMoveEvent : personMoveEvent ) : void
 2003 Prentice Hall, Inc. All rights reserved.