100% found this document useful (2 votes)
34 views81 pages

Graphics Java 2D 1st Edition by Asura ISBN pdf download

The document provides information about various ebooks related to Java graphics, including titles like 'Graphics Java 2D 1st Edition' and 'Introduction to Computer Graphics Using Java 2D and 3D'. It includes links for downloading these ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, the document features exercises and examples related to Java 2D graphics programming.

Uploaded by

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

Graphics Java 2D 1st Edition by Asura ISBN pdf download

The document provides information about various ebooks related to Java graphics, including titles like 'Graphics Java 2D 1st Edition' and 'Introduction to Computer Graphics Using Java 2D and 3D'. It includes links for downloading these ebooks in multiple formats such as PDF, ePub, and MOBI. Additionally, the document features exercises and examples related to Java 2D graphics programming.

Uploaded by

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

Graphics Java 2D 1st Edition by Asura ISBN pdf

download

https://ebookball.com/product/graphics-java-2d-1st-edition-by-
asura-isbn-13486/

Explore and download more ebooks or textbooks


at ebookball.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Graphics Java 2D 1st Edition by Asura ISBN

https://ebookball.com/product/graphics-java-2d-1st-edition-by-
asura-isbn-13482/

Introduction to Computer Graphics Using Java 2D and 3D Undergraduate


Topics in Computer Science 1st Edition by Frank Klawonn ISBN
1447127323 9781447127321

https://ebookball.com/product/introduction-to-computer-graphics-
using-java-2d-and-3d-undergraduate-topics-in-computer-
science-1st-edition-by-frank-klawonn-
isbn-1447127323-9781447127321-19850/

Progresses in the Analysis of Stochastic 2D Cellular Automata A Study


of Asynchronous 2D Minority 1st Edition by Damien Regnault, Nicolas
Schabanel, Eric Thierry ISBN 9783540744566

https://ebookball.com/product/progresses-in-the-analysis-of-
stochastic-2d-cellular-automata-a-study-of-
asynchronous-2d-minority-1st-edition-by-damien-regnault-nicolas-
schabanel-eric-thierry-isbn-9783540744566-11508/

Focus On 2D in Direct3D 1st Edition by Ernest Pazera ISBN 1931841101


9781931841108

https://ebookball.com/product/focus-on-2d-in-direct3d-1st-
edition-by-ernest-pazera-isbn-1931841101-9781931841108-10320/
Java Classes in Java Applications 1st Edition by David Etheridge ISBN

https://ebookball.com/product/java-classes-in-java-
applications-1st-edition-by-david-etheridge-isbn-12866/

Delphi Graphics and Game Programming Exposed with DirectX For versions
5 0 7 0 Table of Contents 1st Edition by Delphi Graphics

https://ebookball.com/product/delphi-graphics-and-game-
programming-exposed-with-directx-for-versions-5-0-7-0-table-of-
contents-1st-edition-by-delphi-graphics-11194/

IDG Books WorldWide 1st Edition by DirectX 3D Graphics Programming


Bible ISBN

https://ebookball.com/product/idg-books-worldwide-1st-edition-by-
directx-3d-graphics-programming-bible-isbn-11082/

Java Enterprise Best Practices 1st Edition by O Reilly Java ISBN


0596003846 9780596003845

https://ebookball.com/product/java-enterprise-best-practices-1st-
edition-by-o-reilly-java-isbn-0596003846-9780596003845-14366/

Java Java Java Object Oriented Problem Solving 3rd Edition by Ralph
Morelli, Ralph Walde ISBN 0131474340 9780131474345

https://ebookball.com/product/java-java-java-object-oriented-
problem-solving-3rd-edition-by-ralph-morelli-ralph-walde-
isbn-0131474340-9780131474345-12410/
12
Graphics and
Java 2D™
One picture is worth ten
thousand words.
—Chinese proverb

Treat nature in terms of the


cylinder, the sphere, the cone,
OBJECTIVES
all in perspective. In this chapter you will learn:
—Paul Cézanne
■ To understand graphics contexts and graphics objects.
Colors, like features, follow ■ To manipulate colors.
the changes of the emotions. ■ To manipulate fonts.
—Pablo Picasso
■ To use methods of class Graphics to draw lines,
rectangles, rectangles with rounded corners, three-
Nothing ever becomes real
dimensional rectangles, ovals, arcs and polygons.
till it is experienced—even a
proverb is no proverb to you ■ To use methods of class Graphics2D from the Java
till your life has illustrated 2D API to draw lines, rectangles, rectangles with rounded
it. corners, ellipses, arcs and general paths.
—John Keats
■ To specify Paint and Stroke characteristics of shapes
displayed with Graphics2D.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
2 Chapter 12 Graphics and Java 2D™

Self-Review Exercises
12.1 Fill in the blanks in each of the following statements:
a) In Java 2D, method of class sets the characteristics of a line
used to draw a shape.
ANS: setStroke, Graphics2D
b) Class helps specify the fill for a shape such that the fill gradually changes
from one color to another.
ANS: GradientPaint
c) The method of class Graphics draws a line between two points.
ANS: drawLine
d) RGB is short for , and .
ANS: red, green, blue
e) Font sizes are measured in units called .
ANS: points
f) Class helps specify the fill for a shape using a pattern drawn in a Buffered-
Image.
ANS: TexturePaint
12.2 State whether each of the following is true or false. If false, explain why.
a) The first two arguments of Graphics method drawOval specify the center coordinate of
the oval.
ANS: False. The first two arguments specify the upper-left corner of the bounding rectan-
gle.
b) In the Java coordinate system, x-values increase from left to right.
ANS: True.
c) Graphics method fillPolygon draws a solid polygon in the current color.
ANS: True.
d) Graphics method drawArc allows negative angles.
ANS: True.
e) Graphics method getSize returns the size of the current font in centimeters.
ANS: False. Font sizes are measured in points.
f) Pixel coordinate (0, 0) is located at the exact center of the monitor.
ANS: False. The coordinate (0,0) corresponds to the upper-left corner of a GUI component
on which drawing occurs.
12.3 Find the error(s) in each of the following and explain how to correct the error(s). Assume
that g is a Graphics object.
a) g.setFont( "SansSerif" );
ANS: The setFont method takes a Font object as an argument—not a String.
b) g.erase( x, y, w, h ); // clear rectangle at (x, y)
ANS: The Graphics class does not have an erase method. The clearRect method should
be used.
c) Font f = new Font( "Serif", Font.BOLDITALIC, 12 );
ANS: Font.BOLDITALIC is not a valid font style. To get a bold italic font, use Font.BOLD +
Font.ITALIC.
d) g.setColor( 255, 255, 0 ); // change color to yellow
ANS: Method setColor takes a Color object as an argument, not three integers.

Exercises
12.4 Fill in the blanks in each of the following statements:

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 3

a) Class of the Java 2D API is used to draw ovals.


ANS: Ellipse2D.
b) Methods draw and fill of class Graphics2D require an object of type
as their argument.
ANS: Shape.
c) The three constants that specify font style are , and
.
ANS: Font.PLAIN, Font.BOLD and Font.ITALIC.
d) Graphics2D method sets the painting color for Java 2D shapes.
ANS: setColor.
12.5 State whether each of the following is true or false. If false, explain why.
a) Graphics method drawPolygon automatically connects the endpoints of the polygon.
ANS: True.
b) Graphics method drawLine draws a line between two points.
ANS: True.
c) Graphics method fillArc uses degrees to specify the angle.
ANS: True.
d) In the Java coordinate system, values on the y-axis increase from left to right.
ANS: False. In the Java coordinate system, values on the y-axis increase from top to bottom.
e) Graphics inherits directly from class Object.
ANS: True.
f) Graphics is an abstract class.
ANS: True.
g) The Font class inherits directly from class Graphics.
ANS: False. Class Font inherits directly from class Object.
12.6 (Concentric Circles Using Method drawArc) Write an application that draws a series of eight
concentric circles. The circles should be separated by 10 pixels. Use Graphics method drawArc.
ANS:

1 // Exercise 12.6 Solution: CirclesJPanel.java


2 // This program draws concentric circles
3 import java.awt.Graphics;
4 import javax.swing.JPanel;
5
6 public class CirclesJPanel extends JPanel
7 {
8 // draw eight Circles separated by 10 pixels
9 public void paintComponent( Graphics g )
10 {
11 super.paintComponent( g );
12
13 // create 8 concentric circles
14 for ( int topLeft = 0; topLeft < 80; topLeft += 10 )
15 {
16 int radius = 160 - ( topLeft * 2 );
17 g.drawArc( topLeft + 10, topLeft + 25, radius, radius, 0, 360 );
18 } // end for
19 } // end method paintComponent
20 } // end class CirclesJPanel

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 12 Graphics and Java 2D™

1 // Exercise 12.6 Solution: Circles.java


2 // This program draws concentric circles
3 import javax.swing.JFrame;
4
5 public class Circles extends JFrame
6 {
7 public static void main( String args[] )
8 {
9 // create frame for CirclesJPanel
10 JFrame frame = new JFrame( "Circles" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 CirclesJPanel circlesJPanel = new CirclesJPanel();
14 frame.add( circlesJPanel ); // add circlesJPanel to frame
15 frame.setSize( 200, 250 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Circles

12.7 (Concentric Circles Using Class Ellipse2D.Double) Modify your solution to Exercise 12.6 to
draw the ovals by using class Ellipse2D.Double and method draw of class Graphics2D.
ANS:

1 // Exercise 12.7 Solution: CirclesJPanel.java


2 // This program draws concentric circles using Graphics2D
3 import java.awt.Graphics;
4 import java.awt.Graphics2D;
5 import java.awt.geom.Ellipse2D;
6 import javax.swing.JPanel;
7
8 public class CirclesJPanel extends JPanel
9 {
10 // draw eight concentric circles separated by 10 pixels
11 public void paintComponent( Graphics g )

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 5

12 {
13 super.paintComponent( g );
14
15 // create 2D by casting g to Graphics 2D
16 Graphics2D g2d = ( Graphics2D ) g;
17
18 for ( int x = 0; x < 80; x += 10 )
19 {
20 int y = 160 - ( x * 2 );
21 g2d.draw( new Ellipse2D.Double( x + 30, x + 30, y, y ) );
22 } // end for
23 } // end method paintComponent
24 } // end class CirclesJPanel

1 // Exercise 12.7 Solution: Concentric.java


2 // This program draws concentric circles using Graphics2D
3 import javax.swing.JFrame;
4
5 public class Concentric extends JFrame
6 {
7 public static void main( String args[] )
8 {
9 // create frame for CirclesJPanel
10 JFrame frame = new JFrame( "Concentric" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 CirclesJPanel circlesJPanel = new CirclesJPanel();
14 frame.add( circlesJPanel ); // add circlesJPanel to frame
15 frame.setSize( 250, 250 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Concentric

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
6 Chapter 12 Graphics and Java 2D™

12.8 (Random Lines Using Class Line2D.Double) Write an application that draws lines of random
lengths, colors and thicknesses. Use class Line2D.Double and method draw of class Graphics2D to
draw the lines.
ANS:

1 // Exercise 12.8 Solution: LinesJPanel.java


2 // This program draws lines of different colors
3 import java.awt.Color;
4 import java.awt.BasicStroke;
5 import java.awt.geom.Line2D;
6 import java.awt.Graphics;
7 import java.awt.Graphics2D;
8 import java.util.Random;
9 import javax.swing.JPanel;
10
11 public class LinesJPanel extends JPanel
12 {
13 private Color colors[] = { Color.GREEN, Color.CYAN, Color.YELLOW,
14 Color.DARK_GRAY, Color.RED, Color.ORANGE,
15 Color.GRAY, Color.PINK, Color.MAGENTA };
16
17 // create 10 lines
18 public void paintComponent( Graphics g )
19 {
20 super.paintComponent( g );
21 setBackground( Color.BLACK ); // set JPanel background
22 Random random = new Random(); // get random number generator
23
24 // create 2D by casting g to Graphics 2D
25 Graphics2D g2d = ( Graphics2D ) g;
26
27 for ( int y = 60; y < 250; y += 20 )
28 {
29 // choose a random color from array
30 int color = random.nextInt( 9 );
31 g2d.setColor( colors[ color ] );
32
33 // choose a random thickness from 1-20
34 int thickness = 1 + random.nextInt( 20 );
35 g2d.setStroke( new BasicStroke( thickness ) );
36
37 // choose a random length and draw line
38 int x1 = 1 + random.nextInt( 199 );
39 g2d.draw( new Line2D.Double( 1, y, x1, y ) );
40 } // end for
41 } // end method paintComponent
42 } // end class LinesJPanel

1 // Exercise 12.8 Solution: Lines2.java


2 // This program draws lines of different colors

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 7

3 import java.awt.Color;
4 import javax.swing.JFrame;
5
6 public class Lines2
7 {
8 public static void main( String args[] )
9 {
10 // create frame for LinesJPanel
11 JFrame frame = new JFrame( "Lines" );
12 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13
14 LinesJPanel linesJPanel = new LinesJPanel();
15 frame.add( linesJPanel ); // add linesJPanel to frame
16 frame.setSize( 300, 300 ); // set frame size
17 frame.setVisible( true ); // display frame
18 } // end main
19 } // end class Lines2

12.9 (Random Triangles) Write an application that displays randomly generated triangles in dif-
ferent colors. Each triangle should be filled with a different color. Use class GeneralPath and meth-
od fill of class Graphics2D to draw the triangles.
ANS:

1 // Exercise 12.9 Solution: TrianglesJPanel.java


2 // Displays randomly generated triangles in different colors.
3 import java.awt.Color;
4 import java.awt.geom.GeneralPath;
5 import java.awt.Graphics;
6 import java.awt.Graphics2D;
7 import java.util.Random;
8 import javax.swing.JPanel;
9
10 public class TrianglesJPanel extends JPanel
11 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 12 Graphics and Java 2D™

12 // draw ten triangles


13 public void paintComponent( Graphics g )
14 {
15 super.paintComponent( g );
16 setBackground( Color.BLACK ); // set JPanel background color
17 Graphics2D g2d = ( Graphics2D ) g; // cast graphics object
18 Random random = new Random(); // get random number generator
19
20 // create a triangle from three random points
21 for ( int i = 0; i < 10; i++ )
22 {
23 // create the object which will be the triangle
24 GeneralPath triangle = new GeneralPath();
25
26 // use method moveTo to start the triangle
27 int x = random.nextInt( 375 ) + 25;
28 int y = random.nextInt( 375 ) + 25;
29 triangle.moveTo( x, y );
30
31 // draw a line to the second point
32 x = random.nextInt( 375 ) + 25;
33 y = random.nextInt( 375 )+ 25;
34 triangle.lineTo( x, y );
35
36 // draw a line to the third point
37 x = random.nextInt( 375 ) + 25;
38 y = random.nextInt( 375 ) + 25;
39 triangle.lineTo( x, y );
40
41 triangle.closePath(); // draw a line back to the initial point
42
43 // choose a random color
44 g2d.setColor( new Color( random.nextInt( 256 ),
45 random.nextInt( 256 ), random.nextInt( 256 ) ) );
46
47 g2d.fill( triangle ); // color the interior of the triangle
48 } // end for
49 } // end method paintComponent
50 } // end class TrianglesJPanel

1 // Exercise 12.9 Solution: Triangles.java


2 // Displays randomly generated triangles in different colors.
3 import javax.swing.JFrame;
4
5 public class Triangles
6 {
7 public static void main( String args[] )
8 {
9 // create frame for TrianglesJPanel
10 JFrame frame = new JFrame( "Drawing Triangles" );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 9

11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 TrianglesJPanel trianglesJPanel = new TrianglesJPanel();
14 frame.add( trianglesJPanel ); // add trianglesJPanel to frame
15 frame.setSize( 400, 400 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Triangles

12.10 (Random Characters) Write an application that randomly draws characters in different font
sizes and colors.
ANS:

1 // Exercise 12.10 Solution: CharactersJPanel.java


2 // Program randomly draws characters
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics;
6 import java.util.Random;
7 import javax.swing.JPanel;
8
9 public class CharactersJPanel extends JPanel
10 {
11 private final int DELAY = 999999;
12
13 // draw characters
14 public void paintComponent( Graphics g )
15 {
16 String fontOptions[] =

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 12 Graphics and Java 2D™

17 { "Serif", "Monospaced", "SansSerif", "Dialog", "DialogInput" };


18 int styleOptions[] =
19 { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
20
21 super.paintComponent( g ); // call superclass's paintComponent
22 Random random = new Random(); // get random number generator
23
24 // randomly choose font name, position and style
25 int fontSize = ( int ) ( 10 + random.nextFloat() * 63 );
26 String fontName = fontOptions[ ( int ) ( random.nextFloat() * 5 ) ];
27 int fontStyle = styleOptions[ ( int ) ( random.nextFloat() * 4 ) ];
28 int x = ( int ) ( random.nextFloat() * 380 );
29 int y = ( int ) ( 50 + random.nextFloat() * 95 );
30 char letters[] = { 'V', 'O', 'L', 'S', '8', '7' };
31
32 // create font from random data
33 Font font = new Font( fontName, fontStyle, fontSize );
34
35 // draw character with random color
36 g.setColor( new Color( ( float ) random.nextFloat(),
37 ( float ) random.nextFloat(), ( float ) random.nextFloat() ) );
38 g.setFont( font );
39 g.drawString( String.valueOf(
40 letters[ ( int ) ( random.nextFloat() * 6 ) ] ), x, y );
41
42 // adding delay is optional the body of the for loop is empty
43 for ( int h = 1; h < DELAY; h++ ) ;
44
45 repaint(); // repaint panel
46 } // end method paintComponent
47 } // end class CharactersJPanel

1 // Exercise 12.10 Solution: Draw.java


2 // Program randomly draws characters
3 import javax.swing.JFrame;
4
5 public class Draw
6 {
7 public static void main( String args[] )
8 {
9 // create frame for CharactersJPanel
10 JFrame frame = new JFrame( "Drawing Characters" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 CharactersJPanel charactersJPanel = new CharactersJPanel();
14 frame.add( charactersJPanel ); // add charactersJPanel to frame
15 frame.setSize( 380, 150 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Draw

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 11

12.11 (Grid Using Method drawLine) Write an application that draws an 8-by-8 grid. Use Graph-
icsmethod drawLine.
ANS:

1 // Exercise 12.11 Solution: GridJPanel.java


2 // This program draws an 8 x 8 grid
3 import java.awt.Graphics;
4 import javax.swing.JPanel;
5
6 public class GridJPanel extends JPanel
7 {
8 // draw a grid using the drawLine method
9 public void paintComponent( Graphics g )
10 {
11 super.paintComponent( g );
12
13 int y = 30, x1 = 30;
14
15 for ( int row = 0; row <= 8; row++, y += 10 )
16 g.drawLine( 30, y, 110, y );
17
18 for ( int column = 0; column <= 8; column++, x1 += 10 )
19 g.drawLine( x1, 30, x1, 110 );
20 } // end method paintComponent
21 } // end class GridJPanel

1 // Exercise 12.11 Solution: Grid1.java


2 // This program draws an 8 x 8 grid

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
12 Chapter 12 Graphics and Java 2D™

3 import javax.swing.JFrame;
4
5 public class Grid1
6 {
7 public static void main( String args[] )
8 {
9 // create frame for GridJPanel
10 JFrame frame = new JFrame( "Grid" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 GridJPanel gridJPanel = new GridJPanel();
14 frame.add( gridJPanel ); // add gridJPanel to frame
15 frame.setSize( 200, 200 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Grid1

12.12 (Grid Using Class Line2D.Double) Modify your solution to Exercise 12.11 to draw the grid
using instances of class Line2D.Double and method draw of class Graphics2D.
ANS:

1 // Exercise 12.12 Solution: GridJPanel.java


2 // This program draws an 8 x 8 grid
3 import java.awt.geom.Line2D;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import javax.swing.JPanel;
7
8 public class GridJPanel extends JPanel
9 {
10 // draw an 8x8 grid
11 public void paintComponent( Graphics g )
12 {
13 super.paintComponent( g );
14
15 int y = 30, x1 = 30;
16 Graphics2D g2d = ( Graphics2D ) g;
17
18 for ( int row = 0; row <= 8; row++, y += 10 )

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13

19 g2d.draw( new Line2D.Double( 30, y, 110, y ) );


20
21 for ( int column = 0; column <= 8; column++, x1 += 10 )
22 g2d.draw( new Line2D.Double( x1, 30, x1, 110 ) );
23 } // end method paintComponent
24 } // end class GridJPanel

1 // Exercise 12.12 Solution: Grid2.java


2 // This program draws an 8 x 8 grid
3 import javax.swing.JFrame;
4
5 public class Grid2
6 {
7 public static void main( String args[] )
8 {
9 // create frame for GridJPanel
10 JFrame frame = new JFrame( "Grid" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 GridJPanel gridJPanel = new GridJPanel();
14 frame.add( gridJPanel ); // add gridJPanel to frame
15 frame.setSize( 200, 200 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Grid2

12.13 (Grid Using Method drawRect) Write an application that draws a 10-by-10 grid. Use the
Graphics method drawRect.
ANS:

1 // Exercise 12.13 Solution: GridJPanel.java


2 // Program draws a 10x10 grid using drawRect().
3 import java.awt.Graphics;
4 import javax.swing.JPanel;
5
6 public class GridJPanel extends JPanel

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
14 Chapter 12 Graphics and Java 2D™

7 {
8 // draw grid
9 public void paintComponent( Graphics g )
10 {
11 super.paintComponent( g ); // call superclass's paintComponent
12
13 for ( int x = 30; x <= 300; x += 30 )
14 for ( int y = 30; y <= 300; y += 30 )
15 g.drawRect( x, y, 30, 30 );
16 } // end method printComponent
17 } // end class GridJPanel

1 // Exercise 12.13 Solution: Grid.java


2 // Program draws a 10x10 grid.
3 import javax.swing.JFrame;
4
5 public class Grid
6 {
7 public static void main( String args[] )
8 {
9 // create frame for GridJPanel
10 JFrame frame = new JFrame( "Drawing a Grid" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 GridJPanel gridJPanel = new GridJPanel();
14 frame.add( gridJPanel ); // add gridJPanel to frame
15 frame.setSize( 400, 420 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Grid

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 15

12.14 (Grid Using Class Rectangle2D.Double) Modify your solution to Exercise 12.13 to draw the
grid by using class Rectangle2D.Double and method draw of class Graphics2D.
ANS:

1 // Exercise 12.14 Solution: Grid2JPanel.java


2 // Program draws 10x10 grid using draw().
3 import java.awt.geom.Rectangle2D;
4 import java.awt.Graphics;
5 import java.awt.Graphics2D;
6 import javax.swing.JPanel;
7
8 public class Grid2JPanel extends JPanel
9 {
10 // draw grid
11 public void paintComponent( Graphics g )
12 {
13 super.paintComponent( g );
14
15 Graphics2D g2d = ( Graphics2D ) g;
16
17 for ( int x = 30; x <= 300; x += 30 )
18 for ( int y = 30; y <= 300; y += 30 )
19 g2d.draw( new Rectangle2D.Double( x, y, 30, 30 ) );
20 } // end method paintComponent
21 } // end class Grid2JPanel

1 // Exercise 12.14 Solution: Grid2.java


2 // Program draws 10x10 grid using draw().
3 import javax.swing.JFrame;
4
5 public class Grid2
6 {
7 public static void main( String args[] )
8 {
9 // create frame for Grid2JPanel
10 JFrame frame = new JFrame( "Drawing grid" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 Grid2JPanel grid2JPanel = new Grid2JPanel();
14 frame.add( grid2JPanel ); // add grid2JPanel to frame
15 frame.setSize( 400, 425 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Grid2

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 12 Graphics and Java 2D™

12.15 (Drawing Tetrahedrons) Write an application that draws a tetrahedron (a three-dimensional


shape with four triangular faces). Use class GeneralPath and method draw of class Graphics2D.
ANS:

1 // Exercise 12.15 Solution: TetrahedronJPanel.java


2 // Program draws a tetrahedron.
3 import java.awt.Color;
4 import java.awt.geom.GeneralPath;
5 import java.awt.Graphics;
6 import java.awt.Graphics2D;
7 import javax.swing.JPanel;
8
9 public class TetrahedronJPanel extends JPanel
10 {
11 // draw tetrahedron
12 public void paintComponent( Graphics g )
13 {
14 super.paintComponent( g );
15
16 int baseX[] = { 110, 150, 50, 110 };
17 int baseY[] = { 90, 130, 130, 90 };
18 int x = 110, y = 40;
19
20 Graphics2D g2d = ( Graphics2D ) g;
21 g2d.setColor( Color.red );
22
23 GeneralPath tetrahedron = new GeneralPath();
24 tetrahedron.moveTo( baseX[ 0 ], baseY[ 0 ] );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 17

25
26 // create path for the tetrahedron
27 for ( int i = 1; i < 4; i++ )
28 {
29 tetrahedron.lineTo( x, y );
30 tetrahedron.moveTo( baseX[ i - 1 ], baseY[ i - 1 ] );
31 tetrahedron.lineTo( baseX[ i ], baseY[ i ] );
32 } // end for
33
34 tetrahedron.closePath();
35 g2d.draw( tetrahedron );
36 } // end method paintComponent
37 } // end class TetrahedronJPanel

1 // Exercise 12.15 Solution: Tetrahedron.java


2 // Program draws a tetrahedron.
3 import javax.swing.JFrame;
4
5 public class Tetrahedron
6 {
7 public static void main( String args[] )
8 {
9 // create frame for TetrahedronJPanel
10 JFrame frame = new JFrame( "Tetrahedron" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 TetrahedronJPanel tetrahedronJPanel = new TetrahedronJPanel();
14 frame.add( tetrahedronJPanel ); // add tetrahedronJPanel to frame
15 frame.setSize( 220, 200 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Tetrahedron

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
18 Chapter 12 Graphics and Java 2D™

12.16 (Drawing Cubes) Write an application that draws a cube. Use class GeneralPath and meth-
od draw of class Graphics2D.
ANS:

1 // Exercise 12.16 Solution: CubeJPanel.java


2 // Program draws a cube.
3 import java.awt.Color;
4 import java.awt.geom.GeneralPath;
5 import java.awt.Graphics;
6 import java.awt.Graphics2D;
7 import javax.swing.JPanel;
8
9 public class CubeJPanel extends JPanel
10 {
11 // draw cube
12 public void paintComponent( Graphics g )
13 {
14 super.paintComponent( g );
15
16 // one base
17 int base1X[] = { 100, 100, 200, 200, 100 };
18 int base1Y[] = { 100, 200, 200, 100, 100 };
19
20 // second base
21 int base2X[] = { 75, 75, 175, 175, 75 };
22 int base2Y[] = { 75, 175, 175 ,75, 75 };
23
24 Graphics2D g2d = ( Graphics2D ) g;
25 g2d.setColor( Color.red );
26
27 GeneralPath cube = new GeneralPath();
28
29 // create path for the cube
30 for ( int i = 1; i <= 4; i++ )
31 {
32 // create the first base
33 cube.moveTo( base1X[ i - 1 ], base1Y[ i - 1 ] );
34 cube.lineTo( base1X[ i ], base1Y[ i ] );
35
36 // create the second base
37 cube.moveTo( base2X[ i - 1 ], base2Y[ i - 1 ] );
38 cube.lineTo( base2X[ i ], base2Y[ i ] );
39
40 // create the lines between the bases
41 cube.moveTo( base1X[ i ], base1Y[ i ] );
42 cube.lineTo( base2X[ i ], base2Y[ i ] );
43 } // end for
44
45 g2d.draw( cube );
46 } // end method paintComponent
47 } // end class CubeJPanel

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 19

1 // Exercise 12.16 Solution: Cube.java


2 // Program draws a cube.
3 import javax.swing.JFrame;
4
5 public class Cube
6 {
7 public static void main( String args[] )
8 {
9 // create frame for CubeJPanel
10 JFrame frame = new JFrame( "Cube" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 CubeJPanel cubeJPanel = new CubeJPanel();
14 frame.add( cubeJPanel ); // add cubeJPanel to frame
15 frame.setSize( 250, 270 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Cube

12.17 (Circles Using Class Ellipse2D.Double) Write an application that asks the user to input the
radius of a circle as a floating-point number and draws the circle, as well as the values of the circle’s
diameter, circumference and area. Use the value 3.14159 for π. [Note: You may also use the pre-
defined constant Math.PI for the value of π. This constant is more precise than the value 3.14159.
Class Math is declared in the java.lang package, so you do not need to import it.] Use the following
formulas (r is the radius):
diameter = 2r
circumference = 2πr
area = πr2

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
20 Chapter 12 Graphics and Java 2D™

The user should also be prompted for a set of coordinates in addition to the radius. Then
draw the circle, and display the circle’s diameter, circumference and area, using an Ellipse2D.Dou-
ble object to represent the circle and method draw of class Graphics2D to display the circle.
ANS:

1 // Exercise 12.17 Solution: CirclesJPanel.java


2 // Program calculates the area, circumference
3 // and diameter for a circle and draws the circle
4 import java.awt.geom.Ellipse2D;
5 import java.awt.Graphics;
6 import java.awt.Graphics2D;
7 import javax.swing.JPanel;
8
9 public class CirclesJPanel extends JPanel
10 {
11 private double radius;
12 private int x;
13 private int y;
14
15 // constructor initialize applet by obtaining values from user
16 public CirclesJPanel( double inputRadius, int inputX, int inputY )
17 {
18 radius = inputRadius;
19 x = inputX;
20 y = inputY;
21 } // end CirclesJPanel constructor
22
23 // draw results on applet's background
24 public void paintComponent( Graphics g )
25 {
26 Graphics2D g2d = ( Graphics2D ) g;
27
28 g.drawString( String.format(
29 "Diameter is %f", ( 2 * radius ) ), 25, 30 );
30 g.drawString( String.format(
31 "Area is %f", ( Math.PI * radius * radius ) ), 25, 45 );
32 g.drawString( String.format(
33 "Circumference is %f", ( 2 * Math.PI * radius ) ), 25, 60 );
34
35 g2d.draw( new Ellipse2D.Double( x, y, radius, radius ) );
36 } // end method paintComponent
37 } // end class CirclesJPanel

1 // Exercise 12.17 Solution: Circle.java


2 // Program calculates the area, circumference
3 // and diameter for a circle and draws the circle
4 import javax.swing.JFrame;
5 import javax.swing.JOptionPane;
6
7 public class Circle

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 21

8 {
9 public static void main( String args[] )
10 {
11 double inputRadius;
12 int inputX;
13 int inputY;
14
15 // create frame for CirclesJPanel
16 JFrame frame = new JFrame( "Circle" );
17 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
18
19 // read from user, convert to proper type
20 inputRadius = Double.parseDouble(
21 JOptionPane.showInputDialog( "Enter radius:" ) );
22 inputX = Integer.parseInt(
23 JOptionPane.showInputDialog( "Enter x-coordinate:" ) );
24 inputY = Integer.parseInt(
25 JOptionPane.showInputDialog( "Enter y-coordinate:" ) );
26
27 CirclesJPanel circlesJPanel =
28 new CirclesJPanel( inputRadius, inputX, inputY );
29 frame.add( circlesJPanel ); // add circlesJPanel to frame
30 frame.setSize( 275, 350 ); // set frame size
31 frame.setVisible( true ); // display frame
32 } // end main
33 } // end class Circle

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
22 Chapter 12 Graphics and Java 2D™

12.18 (Screen Saver) Write an application that simulates a screen saver. The application should
randomly draw lines using method drawLine of class Graphics. After drawing 100 lines, the appli-
cation should clear itself and start drawing lines again. To allow the program to draw continuously,
place a call to repaint as the last line in method paintComponent. Do you notice any problems with
this on your system?
ANS:

1 // Exercise 12.18 Solution: Saver1JPanel.java


2 // Program simulates a simple screen saver
3 import java.awt.Color;
4 import java.awt.Graphics;
5 import javax.swing.JPanel;
6
7 public class Saver1JPanel extends JPanel
8 {
9 private final int DELAY = 9999999;
10
11 // draw lines
12 public void paintComponent( Graphics g )
13 {
14 super.paintComponent( g ); // call superclass's paintComponent
15
16 int x, y, x1, y1;
17
18 // draw 100 random lines
19 for ( int i = 0; i < 100; i++ )
20 {
21 x = ( int ) ( Math.random() * 300 );
22 y = ( int ) ( Math.random() * 300 );
23 x1 = ( int ) ( Math.random() * 300 );
24 y1 = ( int ) ( Math.random() * 300 );
25
26 g.setColor( new Color( ( float ) Math.random(),
27 ( float ) Math.random(), ( float ) Math.random() ) );
28 g.drawLine( x, y, x1, y1 );
29
30 // slow the drawing down. the body of the for loop is empty
31 for ( int q = 1; q < DELAY; q++ ) ;
32 } // end outer for
33
34 repaint(); // repaint component
35 } // end method paintComponent
36 } // end class Saver1JPanel

1 // Exercise 12.18 Solution: Saver1.java


2 // Program simulates a simple screen saver
3 import javax.swing.JFrame;
4
5 public class Saver1
6 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 23

7 public static void main( String args[] )


8 {
9 // create frame for Saver1JPanel
10 JFrame frame = new JFrame( "Saver1" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 Saver1JPanel saver1JPanel = new Saver1JPanel();
14 frame.add( saver1JPanel ); // add saver1JPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Saver1

12.19 (Screen Saver Using Timer) Package javax.swing contains a class called Timer that is capable
of calling method actionPerformed of interface ActionListener at a fixed time interval (specified
in milliseconds). Modify your solution to Exercise 12.18 to remove the call to repaint from method
paintComponent. Declare your class to implement ActionListener. (The actionPerformed method
should simply call repaint.) Declare an instance variable of type Timer called timer in your class.
In the constructor for your class, write the following statements:

timer = new Timer( 1000, this );


timer.start();

This creates an instance of class Timer that will call this object’s actionPerformed method every
1000 milliseconds (i.e., every second).
ANS:

1 // Exercise 12.19 Solution: SaverJPanel.java


2 // Program simulates a simple screen saver
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.Graphics;
7 import java.util.Random;

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
24 Chapter 12 Graphics and Java 2D™

8 import javax.swing.JPanel;
9 import javax.swing.Timer;
10
11 public class SaverJPanel extends JPanel implements ActionListener
12 {
13 private final int DELAY = 9999999;
14 private Timer timer;
15
16 // constructor sets window's title bar string and dimensions
17 public SaverJPanel()
18 {
19 timer = new Timer( 1000, this ); // create the timer
20 timer.start();
21 } // end SaverJPanel constructor
22
23 // draw lines
24 public void paintComponent( Graphics g )
25 {
26 super.paintComponent( g );
27 Random random = new Random(); // creat random number generator
28
29 int x, y, x1, y1;
30
31 for ( int i = 0; i < 100; i++ )
32 {
33 x = random.nextInt( 300 );
34 y = random.nextInt( 300 );
35 x1 = random.nextInt( 300 );
36 y1 = random.nextInt( 300 );
37
38 g.setColor( new Color( random.nextFloat(),
39 random.nextFloat(), random.nextFloat() ) );
40 g.drawLine( x, y, x1, y1 );
41
42 // slow the drawing down. the body of the for loop is empty
43 for ( int q = 1; q < DELAY; q++ ) ;
44 } // end for
45 } // end method paintComponent
46
47 // repaint JPanel
48 public void actionPerformed( ActionEvent actionEvent )
49 {
50 repaint();
51 } // end method actionPerformed
52 } // end class SaverJPanel

1 // Exercise 12.19 Solution: Saver2.java


2 // Program simulates a simple screen saver
3 import javax.swing.JFrame;
4
5 public class Saver2
6 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 25

7 public static void main( String args[] )


8 {
9 // create frame for SaverJPanel
10 JFrame frame = new JFrame( "Saver2" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 SaverJPanel saverJPanel = new SaverJPanel();
14 frame.add( saverJPanel ); // add saverJPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Saver2

12.20 (Screen Saver for a Random Number of Lines) Modify your solution to Exercise 12.19 to en-
able the user to enter the number of random lines that should be drawn before the application clears
itself and starts drawing lines again. Use a JTextField to obtain the value. The user should be able
to type a new number into the JTextField at any time during the program’s execution. Use an inner
class to perform event handling for the JTextField.
ANS:

1 // Exercise 12.20 Solution: SaverJPanel.java


2 // Program simulates a simple screen saver
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.FlowLayout;
7 import java.awt.Graphics;
8 import java.util.Random;
9 import javax.swing.JPanel;
10 import javax.swing.JTextField;
11 import javax.swing.Timer;
12
13 public class SaverJPanel extends JPanel implements ActionListener
14 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
26 Chapter 12 Graphics and Java 2D™

15 private final int DELAY = 9999999;


16 private Timer timer;
17 private int numberLines;
18
19 private JTextField input;
20
21 // constructor sets window's title bar string and dimensions
22 public SaverJPanel()
23 {
24 numberLines = 100; // initialize the number of lines to draw
25
26 timer = new Timer( 1000, this ); // create the timer
27 timer.start();
28
29 input = new JTextField( 10 );
30 input.addActionListener(
31
32 new ActionListener() // anonymous inner class
33 {
34 public void actionPerformed( ActionEvent event )
35 {
36 numberLines = Integer.parseInt( input.getText() );
37 } // end method actionPerformed
38 } // end anonymous inner class
39 ); // end call to addActionListner
40
41 setLayout( new FlowLayout() );
42 add( input );
43 } // end SaverJPanel constructor
44
45 // draw lines
46 public void paintComponent( Graphics g )
47 {
48 super.paintComponent( g );
49 Random random = new Random(); // create random number generator
50 int x, y, x1, y1;
51
52 for ( int i = 0; i < numberLines; i++ )
53 {
54 x = random.nextInt( 300 );
55 y = random.nextInt( 300 );
56 x1 = random.nextInt( 300 );
57 y1 = random.nextInt( 300 );
58
59 g.setColor( new Color( random.nextFloat(),
60 random.nextFloat(), random.nextFloat() ) );
61 g.drawLine( x, y, x1, y1 );
62
63 // slow the drawing down. the body of the for loop is empty
64 for ( int q = 1; q < DELAY; q++ ) ;
65 } // end for
66 } // end method paintComponent
67
68 // repaint JPanel

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 27

69 public void actionPerformed( ActionEvent actionEvent )


70 {
71 repaint();
72 } // end method actionPerformed
73 } // end class SaverJPanel

1 // Exercise 12.20 Solution: Saver3.java


2 // Program simulates a simple screen saver
3 import javax.swing.JFrame;
4
5 public class Saver3
6 {
7 public static void main( String args[] )
8 {
9 // create frame for SaverJPanel
10 JFrame frame = new JFrame( "Saver3" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 SaverJPanel saverJPanel = new SaverJPanel();
14 frame.add( saverJPanel ); // add saverJPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Saver3

12.21 (Screen Saver with Shapes) Modify your solution to Exercise 12.19 such that it uses random-
number generation to choose different shapes to display. Use methods of class Graphics.
ANS:

1 // Exercise 12.21 Solution: SaverJPanel.java


2 // Program simulates a simple screen saver

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
28 Chapter 12 Graphics and Java 2D™

3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.Graphics;
7 import java.util.Random;
8 import javax.swing.JPanel;
9 import javax.swing.Timer;
10
11 public class SaverJPanel extends JPanel implements ActionListener
12 {
13 private final int DELAY = 9999999;
14 private Timer timer;
15 private Random random;
16
17 // constructor sets window's title bar string and dimensions
18 public SaverJPanel()
19 {
20 random = new Random(); // create random number generator
21 timer = new Timer( 1000, this ); // create the timer
22 timer.start();
23 } // end SaverJPanel constructor
24
25 // draw shapes
26 public void paintComponent( Graphics g )
27 {
28 super.paintComponent( g );
29 int shape;
30
31 for ( int i = 0; i < 100; i++ )
32 {
33 shape = random.nextInt( 4 ); // pick a random shape
34
35 // draw different shapes
36 switch( shape )
37 {
38 case 0:
39 makeLine( g );
40 break;
41 case 1:
42 makeRect( g );
43 break;
44 case 2:
45 makeOval( g );
46 break;
47 case 3:
48 makeRoundRect( g );
49 break;
50 } // end switch
51
52 // slow the drawing down. the body of the for loop is empty
53 for ( int q = 1; q < DELAY; q++ ) ;
54 } // end for
55 } // end method paintComponent
56

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 29

57 // repaint JPanel
58 public void actionPerformed( ActionEvent actionEvent )
59 {
60 repaint();
61 } // end method actionPerformed
62
63 // draw a random lines
64 private void makeLine( Graphics g )
65 {
66 int x = random.nextInt( 300 );
67 int y = random.nextInt( 300 );
68 int x1 = random.nextInt( 300 );
69 int y1 = random.nextInt( 300 );
70
71 g.setColor( new Color( random.nextFloat(),
72 random.nextFloat(), random.nextFloat() ) );
73 g.drawLine( x, y, x1, y1 );
74 } // end method makeLine
75
76 // draw a random rectangle
77 private void makeRect( Graphics g )
78 {
79 int x = random.nextInt( 300 );
80 int y = random.nextInt( 300 );
81 int width = random.nextInt( 100 );
82 int height = random.nextInt( 100 );
83
84 g.setColor( new Color( random.nextFloat(),
85 random.nextFloat(), random.nextFloat() ) );
86 g.drawRect( x, y, width, height );
87 } // end method makeRect
88
89 // draw a random oval
90 private void makeOval( Graphics g )
91 {
92 int x = random.nextInt( 300 );
93 int y = random.nextInt( 300 );
94 int width = random.nextInt( 100 );
95 int height = random.nextInt( 100 );
96
97 g.setColor( new Color( random.nextFloat(),
98 random.nextFloat(), random.nextFloat() ) );
99 g.drawOval( x, y, width, height );
100 } // end method makeOval
101
102 // draw a random rounded rectangle
103 private void makeRoundRect( Graphics g )
104 {
105 int x = random.nextInt( 300 );
106 int y = random.nextInt( 300 );
107 int width = random.nextInt( 100 );
108 int height = random.nextInt( 100 );
109 int arcWidth = random.nextInt() * width;
110 int arcHeight = random.nextInt() * height;

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
30 Chapter 12 Graphics and Java 2D™

111
112 g.setColor( new Color( random.nextFloat(),
113 random.nextFloat(), random.nextFloat() ) );
114 g.drawRoundRect( x, y, width, height, arcWidth, arcHeight );
115 } // end method makeRoundRect
116 } // end class SaverJPanel

1 // Exercise 12.21 Solution: Saver4.java


2 // Program simulates a simple screen saver
3 import javax.swing.JFrame;
4
5 public class Saver4
6 {
7 public static void main( String args[] )
8 {
9 // create frame for SaverJPanel
10 JFrame frame = new JFrame( "Saver4" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 SaverJPanel saverJPanel = new SaverJPanel();
14 frame.add( saverJPanel ); // add saverJPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Saver4

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 31

12.22 (Screen Saver Using the Java 2D API) Modify your solution to Exercise 12.21 to use classes
and drawing capabilities of the Java 2D API. Draw shapes like rectangles and ellipses with randomly
generated gradients. Use class GradientPaint to generate the gradient.
ANS:

1 // Exercise 12.22 Solution: SaverJPanel.java


2 // Program simulates a simple screen saver
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.geom.Ellipse2D;
7 import java.awt.geom.Line2D;
8 import java.awt.geom.Rectangle2D;
9 import java.awt.geom.RoundRectangle2D;
10 import java.awt.GradientPaint;
11 import java.awt.Graphics;
12 import java.awt.Graphics2D;
13 import java.util.Random;
14 import javax.swing.JPanel;
15 import javax.swing.Timer;
16
17 public class SaverJPanel extends JPanel implements ActionListener
18 {
19 private final int DELAY = 9999999;
20 private Timer timer;
21 private Random random;
22
23 // constructor sets window's title bar string and dimensions
24 public SaverJPanel()
25 {
26 random = new Random(); // create random number generator
27 timer = new Timer( 1000, this ); // create a new timer
28 timer.start();
29 } // end SaverJPanel constructor
30
31 // draw shapes
32 public void paintComponent( Graphics g )
33 {
34 super.paintComponent( g );
35
36 int shape;
37
38 // draw 100 different shapes
39 for ( int i = 0; i < 100; i++ )
40 {
41 shape = random.nextInt( 4 ); // pick a random shape
42
43 switch( shape )
44 {
45 case 0:
46 makeLine( g );
47 break;
48 case 1:
49 makeRect( g );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
32 Chapter 12 Graphics and Java 2D™

50 break;
51 case 2:
52 makeOval( g );
53 break;
54 case 3:
55 makeRoundRect( g );
56 break;
57 } // end switch
58
59 // slow the drawing down. the body of the for loop is empty
60 for ( int q = 1; q < DELAY; q++ ) ;
61 } // end for
62 } // end method paintComponent
63
64 // repaint JPanel
65 public void actionPerformed( ActionEvent actionEvent )
66 {
67 repaint();
68 } // end method actionPerformed
69
70 // draw a random lines
71 private void makeLine( Graphics g )
72 {
73 Graphics2D g2d = ( Graphics2D ) g;
74
75 double x = random.nextDouble() * 300;
76 double y = random.nextDouble() * 300;
77 double x1 = random.nextDouble() * 300;
78 double y1 = random.nextDouble() * 300;
79
80 g2d.setPaint( new GradientPaint( ( int ) x, ( int ) y,
81 new Color( random.nextFloat(), random.nextFloat(),
82 random.nextFloat() ), ( int ) x1, ( int ) y1,
83 new Color( random.nextFloat(), random.nextFloat(),
84 random.nextFloat() ), true ) );
85
86 g2d.draw( new Line2D.Double( x, y, x1, y1 ) );
87 } // end method makeline
88
89 // draw a random rectangle
90 private void makeRect( Graphics g )
91 {
92 Graphics2D g2d = ( Graphics2D ) g;
93
94 double x = random.nextDouble() * 300;
95 double y = random.nextDouble() * 300;
96 double width = random.nextDouble() * 100;
97 double height = random.nextDouble() * 100;
98
99 g2d.setPaint( new GradientPaint( ( int ) x, ( int ) y,
100 new Color( random.nextFloat(), random.nextFloat(),
101 random.nextFloat() ), ( int )( x + width ),
102 ( int )( y + height ),
103 new Color( random.nextFloat(), random.nextFloat(),
104 random.nextFloat() ), true ) );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 33

105
106 g2d.draw( new Rectangle2D.Double( x, y, width, height ) );
107 } // end method makeRect
108
109 // draw a random oval
110 private void makeOval( Graphics g )
111 {
112 Graphics2D g2d = ( Graphics2D ) g;
113
114 double x = random.nextDouble() * 300;
115 double y = random.nextDouble() * 300;
116 double width = random.nextDouble() * 100;
117 double height = random.nextDouble() * 100;
118
119 g2d.setPaint( new GradientPaint( ( int ) x, ( int ) y,
120 new Color( random.nextFloat(), random.nextFloat(),
121 random.nextFloat() ), ( int )( x + width ),
122 ( int )( y + height ),
123 new Color( random.nextFloat(), random.nextFloat(),
124 random.nextFloat() ), true ) );
125
126 g2d.draw( new Ellipse2D.Double( x, y, width, height ) );
127 } // end method makeOval
128
129 // create a random rounded rectangle
130 private void makeRoundRect( Graphics g )
131 {
132 Graphics2D g2d = ( Graphics2D ) g;
133
134 double x = random.nextDouble() * 300;
135 double y = random.nextDouble() * 300;
136 double width = random.nextDouble() * 100;
137 double height = random.nextDouble() * 100;
138 double arcWidth = random.nextDouble() * width;
139 double arcHeight = random.nextDouble() * height;
140
141 g2d.setPaint( new GradientPaint( ( int ) x, ( int ) y,
142 new Color( random.nextFloat(), random.nextFloat(),
143 random.nextFloat() ), ( int )( x + width ),
144 ( int )( y + height ),
145 new Color( random.nextFloat(), random.nextFloat(),
146 random.nextFloat() ), true ) );
147
148 g2d.draw( new RoundRectangle2D.Double( x, y, width, height,
149 arcWidth, arcHeight ) );
150 } // end method makeRoundRect
151 } // end class SaverJPanel

1 // Exercise 12.22 Solution: Saver5.java


2 // Program simulates a simple screen saver
3 import javax.swing.JFrame;

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
34 Chapter 12 Graphics and Java 2D™

4
5 public class Saver5
6 {
7 public static void main( String args[] )
8 {
9 // create frame for SaverJPanel
10 JFrame frame = new JFrame( "Saver5" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 SaverJPanel saverJPanel = new SaverJPanel();
14 frame.add( saverJPanel ); // add saverJPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Saver5

12.23 (Turtle Graphics) Modify your solution to Exercise 7.21—Turtle Graphics—to add a graph-
ical user interface using JTextFields and JButtons. Draw lines rather than asterisks (*). When the
turtle graphics program specifies a move, translate the number of positions into a number of pixels
on the screen by multiplying the number of positions by 10 (or any value you choose). Implement
the drawing with Java 2D API features.
ANS:

1 // Exercise 12.23: TurtleJPanel.java


2 // Drawing turtle graphics based on turtle commands.
3 import java.awt.Color;
4 import java.awt.event.ActionListener;
5 import java.awt.event.ActionEvent;
6 import java.awt.FlowLayout;
7 import java.awt.geom.Line2D;
8 import java.awt.Graphics;
9 import java.awt.Graphics2D;
10 import javax.swing.JButton;
11 import javax.swing.JPanel;

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 35

12 import javax.swing.JTextField;
13
14 public class TurtleJPanel extends JPanel
15 {
16 // an array of turtle commands
17 private static final int MAXCOMMANDS = 10;
18 private int commandArray[][] = new int [ MAXCOMMANDS ][ 2 ];
19
20 // state variables
21 private int direction;
22 private int count;
23 private int xPos;
24 private int yPos;
25 private boolean penDown;
26 private boolean print;
27
28 private JTextField input;
29 private JButton downJButton;
30 private JButton upJButton;
31 private JButton moveJButton;
32 private JButton turnRightJButton;
33 private JButton turnLeftJButton;
34 private JButton printJButton;
35 private JButton clearJButton;
36
37 private static final int PEN_UP = 1, PEN_DOWN = 2,
38 TURN_RIGHT = 3, TURN_LEFT = 4, MOVE = 5;
39
40 // constructor sets up GUI components and initialize variables
41 public TurtleJPanel()
42 {
43 upJButton = new JButton( "Pen Up" );
44 upJButton.addActionListener(
45 new ActionListener () // anonymous inner class
46 {
47 public void actionPerformed( ActionEvent event )
48 {
49 commandArray[ count ][ 0 ] = PEN_UP;
50 count++;
51
52 if ( count == MAXCOMMANDS )
53 {
54 upJButton.setEnabled( false );
55 downJButton.setEnabled( false );
56 moveJButton.setEnabled( false );
57 input.setEnabled( false );
58 turnRightJButton.setEnabled( false );
59 turnLeftJButton.setEnabled( false );
60 } // end if
61 } // end method actionPerformed
62 } // end anonymous inner class
63 ); // end call to addActionListener
64
65 downJButton = new JButton( "Pen Down" );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
36 Chapter 12 Graphics and Java 2D™

66 downJButton.addActionListener(
67 new ActionListener() // anonymous inner class
68 {
69 public void actionPerformed( ActionEvent event )
70 {
71 commandArray[ count ][ 0 ] = PEN_DOWN;
72 count++;
73
74 if ( count == MAXCOMMANDS )
75 {
76 upJButton.setEnabled( false );
77 downJButton.setEnabled( false );
78 moveJButton.setEnabled( false );
79 input.setEnabled( false );
80 turnRightJButton.setEnabled( false );
81 turnLeftJButton.setEnabled( false );
82 } // end if
83 } // end method actionPerformed
84 } // end anonymous inner class
85 ); // end call to addActionListener
86
87 moveJButton = new JButton( "Move forward" );
88 moveJButton.addActionListener(
89 new ActionListener() // anonymous inner class
90 {
91 public void actionPerformed( ActionEvent event )
92 {
93 // get the distance to move
94 int spaces = Integer.parseInt( input.getText() );
95 input.setText( "" );
96
97 commandArray[ count ][ 0 ] = MOVE;
98 commandArray[ count ][ 1 ] = spaces;
99
100 count++;
101
102 if ( count == MAXCOMMANDS )
103 {
104 upJButton.setEnabled( false );
105 downJButton.setEnabled( false );
106 moveJButton.setEnabled( false );
107 input.setEnabled( false );
108 turnRightJButton.setEnabled( false );
109 } // end if
110 } // end method actionPerformed
111 } // end anonymous inner class
112 ); // end call to addActionListener
113
114 input = new JTextField( 4 );
115 input.addActionListener(
116 new ActionListener () // anonymous inner class
117 {
118 public void actionPerformed( ActionEvent event )
119 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 37

120 // get the distance to move


121 int spaces = Integer.parseInt( input.getText() );
122 input.setText( "" );
123
124 commandArray[ count ][ 0 ] = MOVE;
125 commandArray[ count ][ 1 ] = spaces;
126
127 count++;
128
129 if ( count == MAXCOMMANDS )
130 {
131 upJButton.setEnabled( false );
132 downJButton.setEnabled( false );
133 moveJButton.setEnabled( false );
134 input.setEnabled( false );
135 turnRightJButton.setEnabled( false );
136 turnLeftJButton.setEnabled( false );
137 } // end if
138 } // end method actionPerformed
139 } // end anonymous inner class
140 ); // end call to addActionListener
141
142 turnRightJButton = new JButton( "Turn right" );
143 turnRightJButton.addActionListener(
144 new ActionListener() // anonymous inner class
145 {
146 public void actionPerformed( ActionEvent event )
147 {
148 commandArray[ count ][ 0 ] = TURN_RIGHT;
149 count++;
150
151 if ( count == MAXCOMMANDS )
152 {
153 upJButton.setEnabled( false );
154 downJButton.setEnabled( false );
155 moveJButton.setEnabled( false );
156 input.setEnabled( false );
157 turnRightJButton.setEnabled( false );
158 turnLeftJButton.setEnabled( false );
159 } // end if
160 } // end method actionPerformed
161 } // end anonymous inner class
162 ); // end call to addActionListener
163
164 turnLeftJButton = new JButton( "Turn left" );
165 turnLeftJButton.addActionListener(
166 new ActionListener() // anonymous inner class
167 {
168 public void actionPerformed( ActionEvent event )
169 {
170 commandArray[ count ][ 0 ] = TURN_LEFT;
171 count++;
172
173 if ( count == MAXCOMMANDS )

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
38 Chapter 12 Graphics and Java 2D™

174 {
175 upJButton.setEnabled( false );
176 downJButton.setEnabled( false );
177 moveJButton.setEnabled( false );
178 input.setEnabled( false );
179 turnRightJButton.setEnabled( false );
180 turnLeftJButton.setEnabled( false );
181 } // end if
182 } // end method actionPerformed
183 } // end anonymous inner class
184 ); // end call to addActionListener
185
186 printJButton = new JButton( "Output drawing" );
187 printJButton.addActionListener(
188 new ActionListener () // anonymous inner class
189 {
190 public void actionPerformed( ActionEvent event )
191 {
192 print = true; // run the commands
193 repaint(); // update drawing
194 } // end method actionPerformed
195 } // end anonymous inner class
196 ); // end call to addActionListener
197
198 clearJButton = new JButton( "Clear drawing" );
199 clearJButton.addActionListener(
200 new ActionListener() // anonymous inner class
201 {
202 public void actionPerformed( ActionEvent event )
203 {
204 repaint(); // clear the application
205 clearCommands(); // clear the command array
206
207 upJButton.setEnabled( true );
208 downJButton.setEnabled( true );
209 moveJButton.setEnabled( true );
210 input.setEnabled( true );
211 turnRightJButton.setEnabled( true );
212 turnLeftJButton.setEnabled( true );
213 } // end method actionPerformed
214 } // end anonymous inner class
215 ); // end call to addActionListener
216
217 setLayout( new FlowLayout() );
218 add( upJButton );
219 add( downJButton );
220 add( moveJButton );
221 add( input );
222 add( turnRightJButton );
223 add( turnLeftJButton );
224 add( printJButton );
225 add( clearJButton );
226
227 print = false; // will set to true when printJButton is clicked

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 39

228 clearCommands();
229 } // end constructor TurtleJPanel
230
231 // draw on JPanel
232 public void paintComponent( Graphics g )
233 {
234 super.paintComponent( g );
235
236 Graphics2D g2d = ( Graphics2D ) g;
237
238 if ( print ) // printJButton is clicked, draw turtle graphics
239 {
240 g2d.setColor( Color.RED );
241 executeCommands( g2d );
242 } // end if
243 } // end method paintComponent
244
245 // reset array commandArray
246 public void clearCommands()
247 {
248 count = 0;
249
250 // initialize array commandArray
251 for ( int i = 0; i < MAXCOMMANDS; i++ )
252 for ( int j = 0; j < 2; j++ )
253 commandArray[ i ][ j ] = 0;
254 } // end method clearCommands
255
256 // execute commands stored in commandArray
257 public void executeCommands( Graphics2D g2d )
258 {
259 // reset the state variables
260 direction = 0;
261 xPos = 150;
262 yPos = 150;
263 penDown = false;
264
265 // continue executing commands until reach the end
266 for ( int commandNumber = 0; commandNumber < count;
267 commandNumber++ )
268 {
269 int command = commandArray[ commandNumber ][ 0 ];
270
271 // determine what command was entered and peform desired action
272 switch ( command )
273 {
274 case PEN_UP:
275 penDown = false;
276 break;
277 case PEN_DOWN:
278 penDown = true;
279 break;
280 case TURN_RIGHT:
281 direction = turnRight( direction );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
40 Chapter 12 Graphics and Java 2D™

282 break;
283 case TURN_LEFT:
284 direction = turnLeft( direction );
285 break;
286 case MOVE:
287 int distance = commandArray[ commandNumber ][ 1 ];
288 movePen( g2d, penDown, direction, distance );
289 break;
290 } // end switch
291 } // end for
292
293 print = false; // reset print
294 } // end method executeCommands
295
296 // method to turn turtle to the right
297 public int turnRight( int d )
298 {
299 return --d < 0 ? 3 : d;
300 } // end method turnRight
301
302 // method to turn turtle to the left
303 public int turnLeft( int d )
304 {
305 return ++d > 3 ? 0 : d;
306 } // end method turnLeft
307
308 // method to move the pen
309 public void movePen( Graphics2D g2d, boolean down, int dir, int dist )
310 {
311 // determine which way to move pen
312 switch ( dir )
313 {
314 case 0: // move down
315 if ( down )
316 g2d.draw( new Line2D.Double(
317 xPos, yPos, xPos, yPos + dist * 10 ) );
318 yPos += dist * 10;
319 break;
320 case 1: // move right
321 if ( down )
322 g2d.draw( new Line2D.Double(
323 xPos, yPos, xPos + dist * 10, yPos ) );
324 xPos += dist * 10;
325 break;
326 case 2: // move up
327 if ( down )
328 g2d.draw( new Line2D.Double(
329 xPos, yPos, xPos, yPos - dist * 10 ) );
330 yPos -= dist * 10;
331 break;
332 case 3: // move left
333 if ( down )
334 g2d.draw( new Line2D.Double(
335 xPos, yPos, xPos - dist * 10, yPos ) );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 41

336 xPos -= dist * 10;


337 break;
338 } // end switch
339 } // end method movePen
340 } // end class TurtleJPanel

1 // Exercise 12.23: TurtleGraphics.java


2 // Drawing turtle graphics based on turtle commands.
3 import javax.swing.JFrame;
4
5 public class TurtleGraphics
6 {
7 public static void main( String args[] )
8 {
9 // create frame for TurtleJPanel
10 JFrame frame = new JFrame( "Turtle Graphics" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 TurtleJPanel turtlePanel = new TurtleJPanel();
14 frame.add( turtlePanel ); // add turtleJPanel to frame
15 frame.setSize( 800, 500 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class TurtleGraphics

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
42 Chapter 12 Graphics and Java 2D™

12.24 (Knight’s Tour) Produce a graphical version of the Knight’s Tour problem (Exercise 7.22,
Exercise 7.23 and Exercise 7.26). As each move is made, the appropriate cell of the chessboard
should be updated with the proper move number. If the result of the program is a full tour or a closed
tour, the program should display an appropriate message. If you like, use class Timer (see
Exercise 12.19) to help animate the Knight’s Tour.
ANS:

1 // Exercise 12.24 Solution: KnightJPanel.java


2 // Knight's Tour - access version runs one tour
3 import java.awt.Color;
4 import java.awt.Font;
5 import java.awt.Graphics;
6 import java.util.Random;
7 import javax.swing.JPanel;
8
9 public class KnightJPanel extends JPanel
10 {
11 private final int DELAY = 8000000;
12 private final int INSET = 40;
13 private boolean done;
14 private boolean closed;
15 private int board[][];
16 private int currentRow;
17 private int currentColumn;
18 private int moveNumber;
19 private int testRow;
20 private int testColumn;
21 private int count;
22 private int minRow;
23 private int minColumn;
24 private int minAccess;
25 private int accessNumber;
26 private int firstMoveRow;
27 private int firstMoveColumn;
28
29 private int access[][] = { { 2, 3, 4, 4, 4, 4, 3, 2 },
30 { 3, 4, 6, 6, 6, 6, 4, 3 },
31 { 4, 6, 8, 8, 8, 8, 6, 4 },
32 { 4, 6, 8, 8, 8, 8, 6, 4 },
33 { 4, 6, 8, 8, 8, 8, 6, 4 },
34 { 4, 6, 8, 8, 8, 8, 6, 4 },
35 { 3, 4, 6, 6, 6, 6, 4, 3 },
36 { 2, 3, 4, 4, 4, 4, 3, 2 } };
37 private int horizontal[] = { 2, 1, -1, -2, -2, -1, 1, 2 };
38 private int vertical[] = { -1, -2, -2, -1, 1, 2, 2, 1 };
39 private Random random;
40
41 // constructor sets up the play
42 public KnightJPanel()
43 {
44 minAccess = 9;
45 board = new int[ 8 ][ 8 ];
46 random = new Random();
47 currentRow = random.nextInt( 8 );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 43

48 currentColumn = random.nextInt( 8 );
49 firstMoveRow = currentRow;
50 firstMoveColumn = currentColumn;
51 } // end KnightJPanel constructor
52
53 // returns if spot is within range and empty
54 public boolean validMove( int row, int column )
55 {
56 return ( row >= 0 && row < 8 && column >= 0 && column < 8
57 && board[ row ][ column ] == 0 );
58 } // end method validMove
59
60 // draw chess board with tour
61 public void paintComponent( Graphics g )
62 {
63 super.paintComponent( g );
64
65 int x1 = 0, y1 = 0;
66
67 // draw black and white patterned chess board
68 for ( int j = 0; j <= 7; j++ )
69 {
70 for ( int k = 0; k <= 7; k++ )
71 {
72 if ( ( k + j ) % 2 == 1 )
73 g.setColor( Color.BLACK );
74 else
75 g.setColor( Color.WHITE );
76
77 g.fillRect( x1 + INSET, y1 + INSET, 20, 20 );
78 x1 += 20;
79 } // end for
80
81 y1 += 20;
82 x1 = 0;
83 } // end for
84
85 // place first move on board the red font is used for emphasis
86 board[ currentRow ][ currentColumn ] = ++moveNumber;
87 g.setColor( Color.RED );
88 g.drawString( "1", INSET + 7 + 20 * currentRow,
89 INSET + 15 + 20 * currentColumn );
90
91 while ( !done )
92 {
93 accessNumber = minAccess;
94
95 // cycle through each column of the current row and
96 // determine the move with the minimum access number
97 for ( int moveType = 0; moveType < board.length; moveType++ )
98 {
99 testRow = currentRow + vertical[ moveType ];
100 testColumn = currentColumn + horizontal[ moveType ];
101

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
44 Chapter 12 Graphics and Java 2D™

102 if ( validMove( testRow, testColumn ) )


103 {
104 if ( access[ testRow ][ testColumn ] < accessNumber )
105 {
106 accessNumber = access[ testRow ][ testColumn ];
107 minRow = testRow;
108 minColumn = testColumn;
109 } // end if
110
111 --access[ testRow ][ testColumn ];
112 } // end if
113 } // end for
114
115 // determine whether the next move has been found
116 if ( accessNumber == minAccess )
117 done = true;
118 else
119 {
120 currentRow = minRow;
121 currentColumn = minColumn;
122 board[ currentRow ][ currentColumn ] = ++moveNumber;
123
124 Font oldFont = g.getFont();
125 Font newFont = new Font( "Monospaced", Font.BOLD, 9 );
126
127 // slow animation
128 for ( int h = 1; h <= DELAY; h++ )
129 ; // do nothing
130
131 // draw the new move onto the board
132 if ( moveNumber != 64 )
133 {
134 g.setFont( newFont );
135 g.drawString( String.valueOf(
136 board[ currentRow ][ currentColumn ] ),
137 INSET + 7 + 20 * currentRow, INSET + 13 + 20 *
138 currentColumn );
139 } // end if
140 else // emphasize move 64 (final one in board)
141 {
142 g.setFont( oldFont );
143 g.drawString( String.valueOf(
144 board[ currentRow ][ currentColumn ] ),
145 INSET + 4 + 20 * currentRow, INSET + 15 + 20 *
146 currentColumn );
147 } // end else
148
149 g.setFont( oldFont );
150 } // end else
151 } // end while
152
153 // if this is the final move, determine whether it is possible to
154 // reach the first square and close the knights tour
155 if ( moveNumber == 64 )

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 45

156 {
157 for ( int moveType = 0; moveType < 8; moveType++ )
158 {
159 testRow = currentRow + vertical[ moveType ];
160 testColumn = currentColumn + horizontal[ moveType ];
161
162 if ( testRow == firstMoveRow &&
163 testColumn == firstMoveColumn )
164 {
165 closed = true;
166 break;
167 } // end if
168 } // end for
169 } // end if
170
171 // draw result
172 if ( moveNumber == 64 && closed == true )
173 g.drawString( "Moves: " + moveNumber +
174 " This was a CLOSED tour!", INSET + 0,
175 INSET + 200 );
176 else if ( moveNumber == 64 )
177 g.drawString( "Moves: " + moveNumber +
178 " This was a full tour!", INSET + 0,
179 INSET + 200 );
180 else
181 g.drawString( "Moves: " + moveNumber +
182 " This was not a full tour.", INSET + 0,
183 INSET + 200 );
184 } // end method paintComponent
185 } // end class KnightJPanel

1 // Exercise 12.24 Solution: Knight.java


2 // Knight's Tour - access version runs one tour
3 import javax.swing.JFrame;
4
5 public class Knight
6 {
7 public static void main( String args[] )
8 {
9 // create frame for KnightJPanel
10 JFrame frame = new JFrame( "Knight's Tour" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 KnightJPanel knightJPanel = new KnightJPanel();
14 frame.add( knightJPanel ); // add knightJPanel to frame
15 frame.setSize( 300, 300 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Knight

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
46 Chapter 12 Graphics and Java 2D™

12.25 (Tortoise and Hare) Produce a graphical version of the Tortoise and Hare simulation
(Exercise 7.28). Simulate the mountain by drawing an arc that extends from the bottom-left corner
of the window to the top-right corner of the window. The tortoise and the hare should race up the
mountain. Implement the graphical output to actually print the tortoise and the hare on the arc for
every move. [Note: Extend the length of the race from 70 to 300 to allow yourself a larger graphics
area.]
ANS:

1 // Exercise 12.25 Solution: RaceJPanel.java


2 // Program simulates the race between the tortoise and the hare.For
3 // graphical purposes the race has been extended to 300. The mountain is
4 // represented by a semicircle using the equation for a
5 // circle: (x-h)^2 + (y-k)^2 = r^2. A slight adjustment was made in the
6 // equation to help compensate for the different directions of the
7 // coordinate systems.
8 import java.awt.Color;
9 import java.awt.Font;
10 import java.awt.Graphics;
11 import java.util.Random;
12 import javax.swing.JPanel;
13
14 public class RaceJPanel extends JPanel
15 {
16 private final int RACE_END = 300;
17 private int tortoise = 1;
18 private int hare = 1;
19 private int timer = 0;
20 private Font f;
21 private Random random;
22
23 public RaceJPanel()
24 {
25 f = new Font( "Monospaced", Font.BOLD, 12 );
26 random = new Random();

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 47

27 } // end RaceJPanel constructor


28
29 public void paintComponent( Graphics g )
30 {
31 super.paintComponent( g );
32
33 g.setFont( f );
34
35 while ( tortoise != RACE_END && hare != RACE_END )
36 {
37 // slow animation
38 for ( int k = 1; k <= 100000; k++ )
39 ; // do nothing
40
41 g.setColor( Color.WHITE );
42 g.fillRect( 0, 0, 320, 270 ); // html size
43 g.setColor( Color.BLACK );
44 g.drawArc( 0, 100, 300, 300, 0, 180 );
45
46 moveHare();
47 moveTortoise();
48 printCurrentPositions( g );
49 ++timer;
50 } // end while
51
52 if ( tortoise >= hare )
53 g.drawString( "Time: " + timer + " TORTOISE WINS!!! YAY!!!",
54 20, 300 );
55 else
56 g.drawString( "Time: " + timer + " Hare wins. Yuch!", 20, 300 );
57 } // end method paintComponent
58
59 public void printCurrentPositions( Graphics g2 )
60 {
61 int yHare, yTortoise;
62
63 yHare = ( int ) ( 250 - Math.sqrt( 150 * 150 -
64 Math.pow( hare - 150, 2 ) ) );
65
66 yTortoise = ( int ) ( 250 - Math.sqrt( 150 * 150 -
67 Math.pow( tortoise - 150, 2 ) ) );
68
69 if ( yHare == yTortoise && hare == tortoise )
70 {
71 g2.drawString( "OUCH!", hare, yHare - 60 );
72 g2.drawString( "H", hare, yHare - 20 ); // make hare jump
73 } // end if
74 else
75 g2.drawString( "H", hare, yHare );
76
77 g2.drawString( "T", tortoise, yTortoise );
78 } // end method printCurrentPositions
79
80 public void moveTortoise()
81 {

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
48 Chapter 12 Graphics and Java 2D™

82 int x = random.nextInt( 10 ) + 1;
83 int tortoiseMoves[] = { 3, 6 };
84
85 if ( x >= 1 && x <= 5 ) // fast plod
86 tortoise += tortoiseMoves[ 0 ];
87 else if ( x == 6 || x == 7 ) // slip
88 tortoise -= tortoiseMoves[ 1 ];
89 else // slow plod
90 ++tortoise;
91
92 if ( tortoise < 1 )
93 tortoise = 1;
94 else if ( tortoise > RACE_END )
95 tortoise = RACE_END;
96 } // end method moveTortoise
97
98 public void moveHare()
99 {
100 int y = random.nextInt( 10 ) + 1;
101 int hareMoves[] = { 9, 12, 2 };
102
103 if ( y == 3 || y == 4 ) // big hop
104 hare += hareMoves[ 0 ];
105 else if ( y == 5 ) // big slip
106 hare -= hareMoves[ 1 ];
107 else if ( y >= 6 && y <= 8 ) // small hop
108 ++hare;
109 else if ( y > 8 ) // small slip
110 hare -= hareMoves[ 2 ];
111
112 if ( hare < 1 )
113 hare = 1;
114 else if ( hare > RACE_END )
115 hare = RACE_END;
116 } // end method moveHare
117 } // end class RaceJPanel

1 // Exercise 12.25 Solution: Race2.java


2 // Program simulates the race between the tortoise and the hare.For
3 // graphical purposes the race has been extended to 300. The mountain is
4 // represented by a semicircle using the equation for a
5 // circle: (x-h)^2 + (y-k)^2 = r^2. A slight adjustment was made in the
6 // equation to help compensate for the different directions of the
7 // coordinate systems.
8 import javax.swing.JFrame;
9
10 public class Race2
11 {
12 public static void main( String args[] )
13 {
14 // create frame for RaceJPanel
15 JFrame frame = new JFrame( "Race" );

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 49

16 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
17
18 RaceJPanel raceJPanel = new RaceJPanel();
19 frame.add( raceJPanel ); // add raceJPanel to frame
20 frame.setSize( 400, 400 ); // set frame size
21 frame.setVisible( true ); // display frame
22 } // end main
23 } // end class Race2

12.26 (Drawing Spirals) Write an application that uses Graphics method drawPolyline to draw a
spiral similar to the one shown in Fig. 12.33.

Fig. 12.33 | Spiral drawn using method drawPolyline.

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
50 Chapter 12 Graphics and Java 2D™

ANS:

1 // Exercise 12.26 Solution: SpiralJPanel.java


2 // Program creates a spiral.
3 import java.awt.Graphics;
4 import javax.swing.JPanel;
5
6 public class SpiralJPanel extends JPanel
7 {
8 private int[] x = { 150, 235, 265, 228, 150, 79, 55, 86,
9 150, 207, 225, 199, 150, 108, 95, 115,
10 150, 178, 185, 171, 150, 136, 135, 143,
11 150 };
12 private int[] y = { 275, 235, 150, 72, 45, 79, 150, 214,
13 235, 207, 150, 101, 85, 108, 150, 185,
14 195, 178, 150, 129, 125, 136, 150, 157,
15 155 };
16
17 public void paintComponent( Graphics g )
18 {
19 super.paintComponent( g );
20
21 g.drawPolyline( x, y, 19 );
22 } // end method paintComponent
23 } // end class SpiralJPanel

1 // Exercise 12.26 Solution: Spiral.java


2 // Program creates a spiral.
3 import javax.swing.JFrame;
4
5 public class Spiral
6 {
7 public static void main( String args[] )
8 {
9 // create frame for SpiralJPanel
10 JFrame frame = new JFrame( "Spiral" );
11 frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
12
13 SpiralJPanel spiralJPanel = new SpiralJPanel();
14 frame.add( spiralJPanel ); // add spiralJPanel to frame
15 frame.setSize( 300, 330 ); // set frame size
16 frame.setVisible( true ); // display frame
17 } // end main
18 } // end class Spiral

© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Another Random Scribd Document
with Unrelated Content
“Good going, Li,” Biff exclaimed. “And you described
Perez Soto?”

“I sure did. And the kamaaina says he thinks it was the


same man. The man came to him, first, but he didn’t
have any boat big enough to suit this man.”

“Well, Li, I think we’re getting somewhere. I want to try


one more thing before we go back. I want to make sure
I was being followed. I think it’s important to know if
any of Perez Soto’s men are still in Hana.”

“Why would they be,” Li demanded, “if Perez Soto and


the doctor are on the Big Island?”

“Don’t forget about Tokawto. I’m sure Perez Soto would


want to know if Tokawto recovers enough to talk.”

“What are you going to do?”

“I’ve got a trick up my sleeve. If someone is following 82


me, it might be because he thinks I might still have that
letter.” Biff took out his address book and tore paper
from the back of it. “You know he might be just stupid
enough to think I was still carrying the letter with me.”

“Guess he’d have to be plenty lolo for that, Biff.”

“Plenty lolo? What does that mean?”

“It means dumb or stupid,” Li replied.

Biff grinned. He took a pencil and scribbled a word on


the paper. Then he stuck the paper in his hip pocket, on
top of his handkerchief.
“We’ll walk over to that boathouse,” Biff said. Halfway
there, he stopped, pulled out his handkerchief, and
wiped his forehead. As he did so, the paper fell to the
ground.

“Come on,” he muttered. The boys entered the


boathouse. They pretended to examine the boats,
allowing themselves several minutes.

“Guess we’ve given our pursuer long enough, if we are


being followed,” Biff decided.

They came back out of the boathouse and retraced their


steps. At the spot where Biff had pulled out his
handkerchief, he stopped again, and looked carefully
about him.

“We’ve been followed, all right. The paper is gone,” Biff


said to Li.

“What did you write on that paper, Biff?”

“‘Lolo,’” Biff said, and the boys burst out laughing. 83

Time had slipped by much faster than Biff and Li


realized. It was midaftenoon when they got back to the
hotel.

“Guess I’ve been so excited I forgot about eating,” Li


said, “but am I ever hungry now!”

“I could eat my way through another luau, Li,” Biff


agreed.

At the front desk of the hotel, they found a message


from their fathers.
“We’re checking out the boat,” Biff’s father had written,
“and getting supplies. Wait for us.”

Biff and Li had a late lunch, took a small siesta, then


had a refreshing swim in the hotel’s pool. It was
growing dark when Mr. Brewster and Hank Mahenili
came back.

“We’ve got the boat, Biff. And it’s a real honey. As trim a
craft as you’d ever want to see.”

“Where is it, Dad?” Biff wanted to see the boat.

“Tied up at the municipal wharf. Know where that is?”

“We sure do. We were down there this afternoon. I


wonder how we missed you.”

Biff then told his father and Mr. Mahenili what he and Li
had learned.

“I felt sure it would be Perez Soto. And he rented a


powerful cabin cruiser?” Mr. Brewster asked.

“That’s right, Dad. Li’s kamaaina friend thinks it was the 84


Monday Dr. Weber disappeared.”

“It all adds up. We can’t get to Hawaii fast enough


now.”

“Are we leaving tonight?” Biff asked.

“About ten o’clock. Have to wait until then for supplies


to be delivered.”

“Gee, is it all right if Li and I dash down to the dock and


look at the boat?”
“Sure. You’ll have time. But don’t stay too long. We’ll be
having dinner in an hour.”

Biff and Li started for the door.

“Hey!” Mr. Brewster called. “Don’t you think you ought


to know the boat’s name? It’s the Easy Action.”

It was growing dark when Biff and Li reached the dock.


There was the trim craft, painted a bright white, with a
golden arrow trimming its sides. Its two masts swayed
gently from side to side in the gently rolling water.

“She’s a beauty, all right,” Biff said to Li as they


approached the boat. “Come on, let’s go aboard.”

Biff felt Li’s hand on his arm, restraining him.

“Hold it, Biff,” Li said in a whisper. “I think I saw


someone on the boat. Let’s duck behind these pineapple
crates.”

85
They peered intently at the yawl’s portholes
The boys secreted themselves. They peered intently at 86
the yawl’s portholes. There was barely enough light to
see.

“There, did you see that!”

Biff nodded his head. They had seen a white-clad figure


flash by one of the portholes.

87
CHAPTER XII
Bomb Away

For several moments Biff and Li remained absolutely


quiet and motionless. They knew someone was on the
boat. But what was he doing?

“Could he be one of the men bringing supplies to the


boat?” Li whispered at last.

Biff shook his head. “No. I don’t think so. You’d see
activity on the deck, too, and a truck somewhere
nearby. No, we’ve got to investigate what that character
is doing.”

“I’ve got an idea, Biff.”

“Let’s have it, Li.”

“Well, look, you know how well I can swim under water. 88
Suppose I slip into the water on this side of the wharf.
Then I’ll swim under it, and I can come up right beside
the boat. I’ll move along from porthole to porthole and
see if I can find out what’s going on in the boat.”

“Sounds okay to me. Good thing we changed into


shorts. Be careful not to make any noise.”
“Me, Biff? I’ll be as quiet as a fish.”

He was, too. There wasn’t even the faintest “ker-plop”


as Li lowered himself over the edge of the dock and
sank into the water.

Biff waited tensely. From behind his stack of pineapple


crates, he could get a good view of the starboard side
of the yawl. He could see right to the water line and the
four portholes just above it.

Moments became minutes, and it seemed to Biff that


the minutes were stretching out much too long. Had Li
met some obstruction beneath the dock? Biff’s worry
was increasing. Finally, he noticed a circle of lightly
rippling water near the bow of the boat. In the center of
the circle, he could just spot Li’s head.

He watched as his friend slowly raised himself by the


boat’s starboard gunnel until his head was even with the
porthole. Noiselessly, Li dropped back into the water
and took two strokes toward the stern. Now he peered
into the second porthole. He repeated the process at
the third porthole and moved on to the fourth. The
fourth must be the one, Biff figured, that was in the
small compartment where the yawl’s auxiliary engine
was located.

Li took a longer time at this porthole. Biff watched him 89


intently through the growing darkness. A slight
movement on the boat caused him to raise his eyes. He
gasped.

Directly over Li stood a man with a small nail keg raised


over his head. He was ready to smash it down on Li’s
head.
“Li! Look out! Duck!”

The Hawaiian boy submerged just as the keg struck the


water at the exact spot where his head had been.

“Jeepers,” Biff thought, “I hope Li got far enough under.”

The keg hurler was running along the deck toward the
boat’s bow. Here he could leap on the dock and make
his getaway.

Biff went into action. He jumped from behind the crates,


reached the boat in six fast strides, and leaped aboard
just as the prowler reached the bow.

Biff grabbed at the man. His arms encircled him, and


Biff in turn felt the man’s arms squeeze him in a bearlike
hug. Biff exerted every ounce of his strength, trying to
force the man over backward, trying to free himself of
the man’s crushing grip.

He heard a noise from directly behind the man. Looking 90


over his shoulder, Biff saw the dripping figure of Li
scramble aboard. Li didn’t hesitate. He threw himself at
the man, striking him just at the knees from the rear.
“Clipping,” flashed through Biff’s mind. Unfair in football,
but in a fight like this there’d be no fifteen-yard penalty.

The impact of Li’s body forced the man to release his


grip. As he did, Biff stepped backward. His feet became
entangled in a coil of rope. He lost his balance, toppling
backward. His feet hit the raised gunnel, and the next
moment he was flying through the air. He felt himself
falling, a sickening feeling, as if he were falling from a
great height. He wasn’t, though. He was falling from the
bow, six feet to the water. But he was falling backward
and had no time sense of the distance.
He hit the water with a splash. His broad back smacked
the water with the noise of a loud handclap. Biff could
feel his back sting from the impact.

He turned over and looked up. There was the bow of


the boat, directly overhead. There was Li, looking down
at him.

“You all right, Biff?” There was a strange sound in Li’s


voice. For a moment, Biff was angered. The strange
sound was Li trying to hold back his laughter. Biff’s
sense of humor came to his rescue. He must have been
a funny sight, thrashing around in the water on his back
like a beached porpoise.

“Yep. I’m all right,” he called. “I’ll swim to midships. You 91


can give me a hand up.”

Once back aboard, Biff’s first concern was about the


prowler.

“Oh, him,” Li said. “When you made your backward


bellywhopper, that guy took off. He raced down the
dock. He’s long gone by now.”

Biff rubbed the small of his back with his left hand.
“That hurt. And here you are laughing at me.”

“You were funny, Biff,” Li laughed. “And that sting won’t


last long.”

“Guess you’re right. Hey, let’s see if we can find out


what our visitor was doing on board.”

First the boys explored the deck of the boat. They


opened the sail-chest and inspected the sails. They
hadn’t been touched. They carefully examined the
yawl’s rigging. Both knew that an important rope could
be cut just far enough through so that it would hold in a
mild wind, then snap in a heavy one, just when it was
most badly needed. No evidence of any tampering with
the rigging.

“Let’s go below. That’s where the prowler was when we


got here. He must have been doing his dirty work down
there,” Biff said.

A careful search of the cabins, each with two berths,


revealed nothing.

“Hey, look at this!” Li called. He was in the engine 92


compartment, a small space between the forward cabin
and the galley. “Doesn’t it look to you as if this has been
moved recently?”

Li pointed to the wooden cover which housed the


engine. It was sitting slightly askew.

“We’ll take a look underneath.” Biff took one side of the


housing, Li the other.

“Careful now. Heave gently.”

They removed the housing.

“Must be a flashlight around here somewhere. Have to


have one if we’re going to find anything.”

Li found one in the tool chest.

Biff took it and directed its beam of light on the top of


the engine.
“Nice little engine. A four-cylinder Indian Marine. Ought
to shove us along around eight or ten knots.”

He placed the light’s beam over the engine, inch by


inch. Suddenly he brought the light’s rays to a fixed
spot. Biff bent low.

“Never saw anything like this on one of these engines.


Take a look, Li.”

Li bent down beside Biff.

The boys were looking at a crudely made object,


resembling a small tin can. It was roughly attached just
below the engine’s carburetor.

“Let’s get out of here,” Biff said, swallowing. His throat


had become dry and tight. “That thing’s a bomb—a
homemade bomb.”

Li was already heading back to the cockpit. 93

“Alloo there! Ship ahoy!” came a cry from the dock.

Biff and Li burst on deck just as his father and Mr.


Mahenili started to step aboard.

“Stay back, Dad! Stay back! There’s a bomb on the


boat!” Biff yelled.

Breathlessly, the boys told their fathers of spotting the


prowler on board, of the brief tussle, and the results of
their investigation.

“It’s a good thing we came down,” Tom Brewster said.


“You were late. We thought you might have run up
against something.”
“We sure did, Dad,” Biff assured him.

“I’ll have to investigate. Can you tell me exactly where


this thing you think is a bomb is located?”

“You’re not going on board, are you, Dad?” Biff asked,


his voice filled with anxiety.

“I think it will be all right. I have an idea that bomb isn’t


intended to go off while the boat’s still in harbor.”

“But, Dad, it might,” Biff protested.

“Biff, I’ve handled dynamite and other types of


explosives in my work. I was also in the bomb
demolition service in the army. I can handle it. You stay
back, though, all of you, until I give you an all-clear.
Now just where is this thing you found?”

“Directly under the carburetor,” Biff replied.

“Here, you’ll need this.” He handed his father the 94


flashlight.

They watched Mr. Brewster’s head disappear as he


moved down the steps from the cockpit to the first
cabin.

“I think we’d better follow your father’s orders, boys,”


Hank Mahenili said. “We’ll put a little distance between
us and the boat—just in case.”

The three moved an anchor rope’s length from the stem


of the boat.

The minutes went by. The waiting became almost


unbearable. Biff couldn’t control the feeling of fear
gnawing at the pit of his stomach. Any moment, he
expected to hear the dull thud of an explosion. He
expected to see the boat burst open, sending wood and
debris flying through the air.

Minutes ticked on. Each one seemed an hour to Biff. At


last, he saw his father emerge from the cockpit.

“I’ve got it. It’s all right.”

Biff ran to where his father stood. It may have been all
right, but Biff could tell by the beads of perspiration
standing out on his father’s forehead and by his soaked
shirt, that it had been a ticklish job.

“It’s a bomb, all right. Perez Soto is playing for keeps,” 95


Mr. Brewster said grimly. He wiped his forehead. “It’s a
simple thing, really. Anyone with Perez Soto’s
experience, or mine, for that matter, could make it.”

“But when was it set to go off?” Biff asked.

“That would depend on when and how long we used


the auxiliary engine. See this timer?”

The three leaned forward for a closer look, peering


warily at the infernal machine Biff’s father held in his
hand.

“This timer, which is hooked up to the detonator, is fixed


so it starts in motion when the engine is started. It cuts
out when the engine is out. Very clever, actually, even
though it is simple.”

“When would the timer fire the charge?” Biff asked.


“I’d judge after about an hour, perhaps two—no more—
after the engine had been running.”

“We’d be out in the middle of the ocean by then.” Biff


looked at Li and Mr. Mahenili. Both shook their heads.

“Worse than that, Biff, if I’ve got it figured right.”

“How, Dad?”

“Well, Perez Soto would know that we’d use the engine
to get us out of the harbor. Maybe a twenty-minute run.
Then we’d go to sail. And we’d use sail every minute we
could. But then—this is the really devilish clever part of
his plan.” Mr. Brewster paused. He turned to Li’s father.

“Didn’t you tell me that there are some dangerous reefs 96


off Ka Lae?”

“You bet there are,” Mr. Mahenili said. “And the water’s
shark-infested, too.”

“Well, to search the coast along there for Huntington’s


sunken sloop, we’d have to use the engine. Couldn’t
take a chance with sail on those ragged coral reefs.”

“I’m beginning to catch on, Dad,” Biff said soberly.

“I expected you would.”

“We’d have to use the engine, as you said. And right in


the midst of those reefs, and those sharks, bang! The
boat would have blown up—”

“And that would have been the end of us,” Thomas


Brewster said quietly. He tossed the deactivated bomb
overboard.
“Rest in pieces,” Biff said fervently.

97
CHAPTER XIII
A Near Miss

“Everything all clear?” Mr. Brewster called out from his


position at the tiller in the yawl, Easy Action.

“Aye, aye, sir,” Biff called back to his father. Biff held on
to the bow line, loosely circled over a piling at the dock.

“Cast off, then,” Tom Brewster ordered.

Biff flicked the rope, snaking it over the piling, as the


Easy Action was cleared. Biff heard the low growl of the
reverse gear as his father backed easily away from the
wharf. A shift to forward, the engine revved up higher,
and the yawl headed out of the harbor at Hana.

It was a clear night, bright stars lighting up the skies 98


over the Hawaiian Islands. A slight sliver of a new moon
could just be seen rising in the east.

The yawl ran on its auxiliary engine for fifteen minutes,


putting the harbor behind it. When they were well clear,
and in open sea, Mr. Brewster cut the engine.

“All hands to,” he called. “Prepare to hoist sail.”


A yawl is a fore-and-aft rigged vessel. It has a large
mainmast forward, and a much smaller mast set abaft
or behind the tiller, or wheel.

Hank Mahenili and his son Li had hold of the halyards at


the mainmast, ready to pull on the lines to raise the
main and jib sails.

Biff would handle the mizzen or aft sail by himself.

“Heave away, me hearties,” Mr. Brewster ordered.

The three “hearties” heaved, and the sails slid up their


masts, and billowed gently out, catching a soft, warm
wind. The sails were set and trimmed.

“Okay, Biff, you take over now.”

Biff came into the cockpit and took the tiller over from
his father.

“Keep her headed as she is now. The compass setting is


for Upolu Point. We ought to make it easily by daybreak,
and then we’ll cruise the western coast of the Big
Island.”

“Heading for Ka Lae, Dad?” Biff asked.

“That’s right, Biff. Hank and I are going to turn in now. 99


You and Li handle the ten-to-two watch. Wake us up at
two, then you boys can grab some sleep.”

Li joined Biff in the cockpit.

The Easy Action lived up to her name. She slid


effortlessly through the water, noiseless except for the
soft swish of her bow cleaving a path. The wind held
steady. There was nothing to do but hold her on course.

“Like sailing, Li?” Biff asked.

“It’s the greatest. I’ll take sail over power any day.” Li
spoke as if he were an old salt.

“Not so good for water skiing, though,” Biff said. “You


need more speed for that, quick speed, fast starts.”

“Oh, sure. But for a cruise like we’re taking, give me


sail.”

The boys were quiet. The spell of the night settled over
them. Li, Biff knew, dozed off from time to time. He
himself felt drowsy, lulled into sleepiness by the slight
rise and fall of the craft as it rode over the swells.

Biff looked at the luminous dial of his watch. It was


nearly twelve o’clock. He nudged the sleeping Li.

“Hey, you’re supposed to be on this watch with me.


How ’bout taking over for a while?”

Li rubbed his eyes, stretched, and yawned.


“Aye, aye, Captain.” He took the tiller. 100

Biff stood up, stretched his body, then settled into a


more comfortable position. He fought off sleep, but
knew he dozed now and again in short, five-minute
catnaps. He was never far from consciousness, though.
And if anything happened—say a quickening of the wind
—he would have been alert immediately.

At two o’clock, a widely yawning Tom Brewster emerged


from the cabin, followed by Hank Mahenili.

“All right, boys. We’ll take over now. Get some sleep. At
this steady pace, we’ll reach Upolu long before daylight.
We’ll drop anchor, then set out again at daybreak.”

Upolu is the northernmost point on the Island of Hawaii.

Biff and Li were asleep the moment they hit their


berths. It seemed to Biff he had only just gone to sleep
when he felt his father shaking his shoulder.

“Rise and shine, Biff. Almost daylight. We’re shoving off


as soon as we have some grub.”

Under a bright morning sun, the Easy Action got under


way again. Biff was at the tiller. His father and Hank
Mahenili, tired from their early morning watch, dozed on
the foredeck in comfortable captain’s chairs.

Biff and Li had their work cut out for them. The course 101
set was a zigzag one. They wanted to cruise as much of
the coastline as possible in the hope of spotting some
sign of Huntington’s sunken sloop.

Biff would head the Easy Action off shore, run out
nearly ten miles, then tack back in. For every three
miles they progressed down the coast toward Ka Lae,
the southern tip of Hawaii, they covered nearly twenty
miles out and back from the coast.

A stiff morning breeze sent the Easy Action skipping


briskly over the waves. They had covered a good
distance by eight bells, twelve o’clock noon.

Biff and Li took turns at the tiller. When Li was the


steerer, Biff stood on the highest point of the foredeck,
near the ship’s bow, scanning the waters on either side
with powerful binoculars. When it was his time to take
over the wheel, Li took up the vigil.

They reached Kailua on the Kona coast as the sun, like


a blazing ball, settled into the Pacific Ocean to the west.
They were halfway to Ka Lae, the southern cape.

The party went ashore for a steak dinner at the famous


Kona Steak House, then came back to their boat filled
with food and tired. All turned in at once. No watch was
set. None of them saw the black-hulled power cruiser
come in and drop its anchor nearby. Then the captain of
the cruiser, having spotted the Easy Action, weighed
anchor and moved off to an anchorage out of sight from
the crew of the yawl.

The next morning the search was continued, the yawl 102
weaving its way in and out along the coast, drawing
nearer to Ka Lae, nearer to the position at which
Huntington had last been heard from.

“I’ll take the tiller now, Biff,’” his father said. “Hank and I
will alternate. I want you and Li to keep a constant
watch. Your young eyes are sharper than ours.”
The Easy Action spent the day crisscrossing a wide area
of water between the shore line and a distance outside
the coral shoals, varying from five to twelve miles.

Nightfall found them off Ka Lae, or South Cape. They


anchored in thirty feet of clear water, about a quarter of
a mile off shore. They could see the white combers
lashing at the rocky formation of the beach.

“We’ll combine our evening meal with a council of war,”


Tom Brewster said, once the ship was made tight for
the night.

“You figure we’re in the danger area now, Dad?” Biff


asked.

“Huntington’s sloop is on the bottom of the ocean


somewhere in this area.”

“And Perez Soto is looking for it just as hard as we are,”


Hank Mahenili added.

“What about Dr. Weber?” Biff asked. “Do you think he’s
aboard Perez Soto’s boat, or do you think he’s being
held on shore?”

“Hard to say, Biff. My feeling is that he’s being held on 103


shore. A captive on a boat could be too easily spotted at
a refueling wharf.”

“Don’t you think, Dad, that we ought to divide up now?”


Biff suggested. “Two of us make a shore search for Dr.
Weber, the other two cruise around and try to spot the
sunken sloop?”

“Good idea, Biff. We’ll do that tomorrow,” Mr. Brewster


agreed. “Hank and I will go ashore. You and Li conduct
the sea search.”

That suited Biff and Li just fine. They looked at one


another and smiled.

“Now tonight, I don’t think it’s necessary to have a


standing watch. There’s been no sign of Perez Soto so
far. But one of us ought to sleep on deck. Any
volunteers?” Biff’s father asked.

“Me, Dad.” Biff jumped at the chance. “I’d love to. Nice
warm night. The sleeping will be better under the stars
than it will be in the cabin.”

“Okay, let’s all turn in. Big day ahead.”

Biff spread out a sleeping bag on the Easy Action’s


foredeck. He lay on his back, his eyes staring up and
the millions of stars twinkling in the sky overhead. The
sound of the surf came distinctly. It was a soothing
sound, and shortly Biff was lulled to sleep.

Some hours later, he was awakened slowly. He heard 104


the distant throb of a powerful engine. At first, Biff
thought it must be an airplane. But then, as he became
wider awake, he realized the throbbing came not from
the air, but the sea. It grew louder as the craft,
whatever it was, drew nearer.

Biff sat up, propping himself on one arm. Now there


was no mistaking it. A boat, one with a powerful engine,
was rapidly approaching the Easy Action’s anchorage.
Biff stood up. He peered into the starlight night. He
could see the reflection of stars twinkling on the water’s
surface. Then he made out the outlines of a cabin
cruiser throwing a fan-tail white wake, heading fast
toward the Easy Action.
“Fools,” Biff muttered to himself, “if they don’t change
course, they’ll ram us.”

He knew the white-hulled yawl was sharply outlined


against the starlit waters. Then he suddenly knew what
was happening. The on-charging cruiser was aiming at
the yawl. It meant to ram her.

Biff raised a cry. It was too late. His voice was drowned
out by the roar of the cruiser’s engines—Biff knew now
that it was a twin-engined craft.

Now the boat seemed on top of the yawl. Its bow, with
a much higher freeboard than the low-lying yawl, reared
up menacingly only twenty feet from the sailing craft.
Surely it would crash them, ram them, send them to the
bottom of the sea, with Biff’s father, Hank Mahenili, and
Li trapped below.

Biff yelled.

At the last moment, the cruiser swerved sharply to the 105


starboard, making an almost right-angle turn. It roared
alongside the Easy Action, not ten feet separating the
two boats.

As the cruiser made its fast, skidding turn, it threw up a


tremendous wave. Biff saw the wave sweeping toward
the yawl. Then, tons of foaming water cascaded over
the Easy Action. Biff grabbed for the mainmast,
wrapping his arms around it in a death lock. He felt the
wave tugging at his body. It took all his strength to
prevent being swept overboard.

The wave passed on over, tumbling gallons of water into


the cabins below.
Biff released his grip on the mainmast. He sprinted to
the cockpit. It was nearly filled with water.

“Dad! Dad! You all right?”

He started to plunge into the water-filled cabin and was


met by his father, Hank, and Li fighting their way out,
gasping for breath, trying to expel water from their
choked lungs.

The black cruiser had sped away, the throb of its


engines barely audible now.

Everyone was all right. But what a mess! Bedding was


soaked. Galley equipment, pots, pans, dishes had been
swept off shelves, some of the pans bobbing like corks
in the swirling waters inside the ship’s cabin.

Biff went into action. Maybe he could start the engine 106
before the water did its damage. He splashed through
the water and reached the engine compartment. He
pulled open the door. It had held back the flood from
the engine room. Before the water could rush in and fill
up that compartment, Biff had the engine going. He
quickly turned on the yawl’s sea pumps. He stood there
with his fingers crossed, hoping the engine wouldn’t
conk out. It didn’t. The heavy-duty pumps worked
perfectly. Already the water inside the boat was
beginning to recede.

Biff joined his father, Hank Mahenili, and Li in the


cockpit. They were still dazed and only now beginning
to breathe easily.

“I thought he was going to ram us, Dad.”

Mr. Brewster shook his head.


“I get it now,” Biff continued. “To ram us would have
damaged his boat—put it out of commission, even if it
didn’t sink. He wanted to swamp us.”

“And nearly did!” Mr. Mahenili said.

The steady beat of the pumps continued. They were


rapidly bailing the yawl out.

“Well, Biff, you know what we’re really up against now,”


his father said seriously.

“I think I always did, Dad. This Perez Soto will stop at


nothing.”

Li sat quietly, but he was shaking as if from a chill. It


was the recent frightening experience which caused him
to tremble.

“Tom, I’ve been in and around water, in and out of 107


boats all my life. But that was the nearest brush I’ve
ever had with a watery grave.” Hank Mahenili’s voice
was solemn. “He’ll never get away with it,” he added
fiercely.

The next hour was spent in straightening up the water


damage. Bedding was brought on deck and spread to
dry. Li was elected cook, to make coffee and hot tea.
Dawn was spreading before the Easy Action was
shipshape again.

After a hot meal, Mr. Brewster took Biff aside.

“Biff, we’re not going to let last night’s incident change


our plans. Hank and I are going ashore immediately.
You and Li put out and start the search at once. We’ve
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like