100% found this document useful (2 votes)
10 views79 pages

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

The document contains information about various books related to Java graphics programming, including titles, authors, and ISBNs. It also provides links for downloading these books in multiple formats such as PDF, ePub, and MOBI. Additionally, the document includes exercises and solutions related to Java 2D graphics, demonstrating how to draw shapes and manipulate graphics contexts.

Uploaded by

tkzhjzoxq165
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)
10 views79 pages

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

The document contains information about various books related to Java graphics programming, including titles, authors, and ISBNs. It also provides links for downloading these books in multiple formats such as PDF, ePub, and MOBI. Additionally, the document includes exercises and solutions related to Java 2D graphics, demonstrating how to draw shapes and manipulate graphics contexts.

Uploaded by

tkzhjzoxq165
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/ 79

Graphics Java 2D 1st Edition by Asura ISBN

download

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

Download more ebook instantly today at https://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.
Other documents randomly have
different content
more. Altered and counterfeit notes to the value of $46,004.95 have
been captured, and counterfeit coins to the value of $19,828.47.
The Chief of the Secret Service says that the year has been fruitful in
that class of criminals who alter bills of small denomination to one of
higher value. Any change in a bill renders the maker liable to a fine
of $5,000, or fifteen years in prison, or both.
The walls of the Secret Service office are covered with samples of
counterfeiters' work. The history of each would sound like a dime
novel, but the government is certain to catch any one who persists
in demoralizing the currency. Chief John E. Wilkie, a first-class
Chicago newspaper man, was brought East by Secretary Gage. He
has called to his assistance, as Chief Clerk, Mr. W. H. Moran, who
learned his business from Mr. Brooks, one of the best detectives any
country has yet produced. Other officials tell me the office has never
been more ably conducted than it is at present.
This bureau is urging that for persistent crime a longer penal
sentence shall be given. To illustrate the persistence of two of these
criminals, the following extracts from the Secret Service records are,
by courtesy of the bureau, submitted:
John Mulvey, alias James Clark, arrested October 16, 1883, at New York, N. Y.,
for having in possession and passing counterfeit coin. Sentenced, October
22, 1883, to three years in Auburn, N. Y., penitentiary and fined $1.
William Stevens, alias John W. Murray, alias Jack Mulvey, was again arrested
June 14, 1886, at Baltimore, for passing counterfeit 25c. silver coins, and
was sentenced, September 7, 1886, to serve one year in Maryland
penitentiary and fined $100.
Was again arrested under the same name October 5, 1887, at Philadelphia,
Pa., for passing and having in possession 25c. coins, and sentenced,
December 1, 1887, to eighteen months in the Eastern Penitentiary of
Pennsylvania and fined.
John W. Murray, alias William Stevens, alias Jack Mulvey, was again arrested,
July 10, 1889, at Hoboken, N. J., for passing counterfeit standard $1, 25c.,
and 10c. coins, and sentenced, January 22, 1890, to six months in State
Prison at Trenton, N. J., and pay costs.
Jack Mulvey, alias James W., alias John Clark, alias John W. Murray, alias "Pants,"
alias Stevens, etc., was again arrested January 12, 1891, at Pittsburg, Pa.,
for having in possession and attempting to pass counterfeit 50c. coins, and
was sentenced, March 5, 1891, to two years in Western Penitentiary at
Allegheny, Pa., and fined $25.
John Murray, alias Jack Mulvey, was again arrested, January 25, 1894, at
Chicago, Ill., for manufacturing counterfeit 25c. and 10c. coins and having
same in possession, and was sentenced, March 12, 1894, to three years
and six months at hard labor in the penitentiary at Joliet, Ill., and to pay a
fine of $1.
James Foley, alias Jack Murray, alias Jack Mulvey, was again arrested, February
24, 1897, at Chicago, Ill., for having in possession and passing counterfeit
silver dimes, and escaped March 22, 1897, but was rearrested, under the
name of John O'Keefe, in New York, N. Y., April 6, 1897, for passing
counterfeit 10c. pieces, and sentenced, May 12, 1897, to seven years in
Clinton Prison and fined $1. Released from this prison February 27, 1902.
Another case from the records of the Secret Service would read as
follows:
One day the doors of the Moundsville, W. Va., prison opened on a
tall, slender, mild-eyed man, upon whose face and form time and
confinement had left their impress, and he passed out to take up
again the broken thread of his life.
This was John Ogle's first day of freedom for more than three years.
On July 4, 1898, he was sentenced to four years' imprisonment for
trying to increase the negotiable value of one-dollar bills by altering
their denominational characteristics.
Little more than a year before his brother, Miles, was released from
the Ohio penitentiary, where he had paid the extreme penalty
imposed by law for spurious money making, only to die two days
later of paralysis, with which he had been hopelessly stricken over a
year before.
The Ogles, father and sons, during the past fifty years have had
much to do with the making of the criminal history of this country.
George Ogle, the father, was a river pirate and farmhouse plunderer,
the Ohio River and its tributaries being the scene of his operations.
The sons, bred in an atmosphere of crime, early embarked in
independent unlawful enterprises. Miles displayed pugnacity,
intrepidity, and skill, while John was shrewd, plausible, and cunning.
After serving five years for killing an officer who attempted to arrest
the family, and when but twenty-six years old, Miles allied himself
with the notorious "Reno" gang of bandits, and became the pupil
and confederate of Peter McCartney, that past master of the
counterfeiter's art. How well he applied himself the records of the
Secret Service will testify. An even dozen skilfully executed spurious
note issues were directly traceable to him, despite the fact that two-
thirds of his manhood were spent behind prison walls.
John Ogle, while not possessed of the dangerous skill of his brother,
was his equal in hardihood, and, in his way, quite as detrimental to
society. For cool daring, ingenuity, and resourcefulness he was
without a peer in his chosen profession, and some of his escapes
from the officers of the law bordered on the miraculous. He was
introduced to prison life in 1864, being sentenced in the fall of that
year to five years in the Jeffersonville, Ind., penitentiary for burglary.
Shortly after his release he was traced to Cairo, Ill., with twenty-
eight hundred dollars of counterfeit money intended for one of Miles'
customers, and, after a desperate fight, was placed in jail. He
managed in some way to effect his escape, but was soon recaptured
at Pittsburg. This time he told the officers that he knew of a big
"plant" of spurious bills and tools near Oyster Point, Md., which he
was willing to turn up if it would benefit him. Being assured of
leniency, he started with a marshal for the hiding-place. En route he
managed to elude the watchfulness of his guard, and jumped from
the car-window while the train was at full speed. At Bolivar, Tenn.,
Ogle was arrested, January 8, 1872, with five hundred dollars of
counterfeit money in his pocket. A sentence of ten years was
imposed; but John had a reputation to sustain, so he broke from the
jail where he was temporarily confined awaiting transportation to the
penitentiary. Several months later he was arrested and indicted at
Cincinnati for passing bad five-dollar bills. Pending trial, he was
released on five thousand dollars bail, which he promptly forfeited,
and was again a fugitive.
February 18, 1873, one Tom Hayes was detected passing counterfeit
money at Cairo, Ill., but it was not discovered that "Tom Hayes" was
none other than the much-wanted John Ogle until after he had
made good his escape. So chagrined were the officers over this
second break that all the resources of the department were
employed to effect his capture, and but a week had passed before
he was found in Pittsburg and taken to Springfield, Ill., for trial. This
time there was no escape, and he served five years in Joliet. As he
stepped from the prison door Marshal Thrall, of Cincinnati,
confronted him with an order for his removal to answer the
indictment of May, 1872. The Cincinnati jail was undergoing repairs.
A painter had left his overalls and hickory shirt in the corridor near
the cage where Ogle was placed. Adroitly picking the lock of his cell
with his penknife, he donned the painter's clothes, took up a paint-
bucket, and coolly walked down-stairs, past the gate (which the
guard obligingly opened for him), through the jailer's office, and into
the street. Proceeding leisurely until out of sight of the prison, the
daring criminal made his way to the river, which he crossed at
Lawrenceburg, and, discarding his borrowed apparel, struck across
the country, finally bringing up at Brandenburg, Ky., where he
obtained employment as a stonecutter. Respectability was, however,
inconsistent with Ogle's early training; so about a week after his
arrival he broke into a shoe-house of the town, stole $200 worth of
goods, and was arrested three days later while trying to dispose of
his plunder in Louisville. Fearing a term in the Frankfort prison for
some reason, he informed the Kentucky officers that a large reward
was offered for his return to Cincinnati. This had the desired effect,
and he was sent to the Ohio penitentiary to serve five years.
Returning to Cincinnati at the expiration of this enforced
confinement, he met his brother, who had just been released from
an eight-year "trick" in the Western Pennsylvania penitentiary, and,
altho no real affection existed in the breast of either for the other,
John needed money, and Miles had money and required assistance
in a contemplated enterprise. An understanding was soon reached,
and these two dangerous lawbreakers joined forces in another
scheme to debase their country's currency. Using the same
conveyance employed by their father in his plundering expedition (a
house-boat), they started from Cincinnati and drifted down the Ohio
River, John steering and keeping watch while Miles plied the graver.
When the plates for a twenty-dollar silver note and a ten-dollar issue
of the Third National Bank of Cincinnati were complete, Miles took
the helm and John went below to do the printing. $150,000 of the
"coney" had been run off by the time they reached the mouth of the
Wolf River, and here the trip ended. Disposing of the boat, the
brothers started back to Cincinnati. En route they quarreled over the
division of the notes, and separated with the understanding that
John was to receive $500 of the proceeds of the first sales.
Miles did not keep faith, and John subsequently assisted the
government officers in locating and securing his brother, who was
arrested in Memphis, Tenn., on Christmas day, 1884, with $6,000 of
the counterfeits in his pockets.
For a number of years thereafter John steered clear of offenses
penalized by the federal statutes, and successfully feigned insanity
when he could not escape punishment for crimes against the State
by any other means.
This is what happened to one town marshal who caught Ogle in the
act of burglarizing a store and failed to appreciate the character of
his prisoner. It was between two and three o'clock in the morning
when the capture was made, and as the lockup was located about a
mile from the scene of the crime, the officer decided to keep the
rogue in his room until morning. Carefully locking the room door and
handcuffing John, he lit his pipe and made himself as comfortable as
possible—so comfortable, in fact, that he was soon fast asleep.
When he awoke his bird had flown, and the officer's watch and
purse were missing.
XVII
POST-OFFICE DEPARTMENT

very man and woman in the republic has a personal


interest in this department of the government. You pay
two cents for a stamp, throw a missive into a box, and
start the machinery which requires 100,000 persons to
run it. If your letter is for the Philippines, you use the
railroad and the ocean steamer, with many relays of men and
engines to perform your bidding. If your letter is for Alaska, you use
the railroad, the steamship, and the reindeer team to deliver it. Not
an hour, day or night, the entire year through, but men are toiling to
hurry your mail to its destination. If your letter is for one of the large
cities, skilful men board the train, and as it approaches its
destination distribute the mail for each district, so that your letter
will not lie for hours in the central office. If your letter is to a busy
farmer who may be in the midst of his harvest and has no time to go
for his mail, one of the government's faithful servants takes that
letter to him. Yet we are much more likely, withal, to growl at Uncle
Sam than to remember the faithful service we receive for so little
money.
The Post-office Department is one which is not yet self-supporting.
The last annual report of the Postmaster-General shows that the
receipts from ordinary postal revenue amounted to
$191,478,663.41. Figures are not at hand for a further revenue to
the department from money-order business, including post-office
orders which were uncalled for. The government expended
$16,910,278.99 more than it received. This deficit is occasioned by
the second-class matter, which includes newspapers and magazines
paying less than cost of transportation. It is also due partly to the
glaring abuse of the franking privilege by members of the Senate
and House. If a description of what some of these men commit to
Uncle Sam to carry for them free of charge were published they
would hide their heads in shame. While this abuse continues we are
not likely to get a one-cent rate on letters, a rate which would
greatly benefit the entire country. Poor people are paying the
postage for these Congressmen.
The United States Post-office Department and the post-office for the
City of Washington are in a building on Pennsylvania Avenue, which
extends over an entire square from Twelfth to Thirteenth Streets, N.
W.
The Postmaster-General is a member of the President's Cabinet. He
receives $12,000 per annum for giving to his country services which
a railroad or great newspaper would consider cheap at $25,000 per
annum. There are four Assistant Postmaster-Generals who receive
each about half as much as their chief. These are appointed by the
President and confirmed by the Senate.
The Postmaster-General makes postal treaties with foreign
governments, by and with the advice of the President, awards
contracts, and directs the management of the domestic and foreign
mails.
The First Assistant Postmaster-General has charge of the salary and
allowance division, free delivery system, post-office supplies, money-
order division, dead-letter office, and the general correspondence.
The Second Assistant Postmaster-General has charge of the contract
division, division of inspection, railway adjustment (which includes
weighing and deciding on what pay shall be given railroads), the
mail equipment division, and foreign mails.
The Third Assistant Postmaster-General has charge of postage
stamps and postmasters' accounts, registry office, and the special
delivery system.
The Fourth Assistant Postmaster-General has the appointment of
many postmasters and of post-office inspectors, and has charge of
the bonds and commissions for postmasters. This last place was
formerly filled by Mr. J. L. Bristow, of Kansas. During the first year of
Mr. Roosevelt's Presidency Mr. Bristow officially decapitated as many
as fifty postmasters a day, and it is claimed it was a slow year in the
business. Of course, for every one who lost his place some other
fellow was made happy. Mr. P. V. De Graw now has the office.
No impure books, pamphlets, or papers are allowed transportation
by the United States mail. Men in this employ have a right to insist
that their work shall not include indecent matter. As far as possible
the government tries to prevent advertisers of dishonest businesses
from using the mails for fraudulent gain. It is to be hoped that the
time may soon come when all financial schemers who now defraud
the wage-earning class by circulars on mining, oil, or industrial stock,
or other doubtful enterprises, shall be obliged to prove to the
government officials that the scheme represented is just what the
circular sets forth. All Building Associations and Insurance
Companies should pass under the same law. Good people would be
glad of this inspection, and bad people make it necessary.
The Postmaster-General recommends that the government have
inspectors appointed who shall see that neither telegraph nor
express companies be permitted to carry matter for lotteries or any
known fraudulent enterprise. The McKinley and Roosevelt
administrations will be noted for the improvement and extension of
the rural delivery system.
The dead-letter office is one of great interest, and is found in the
general post-office building. Of unclaimed letters there were last
year nearly six million; of misdirected letters, 454,000; and of letters
without any address, 39,837. Any letter which is unclaimed at a post-
office after a few weeks is sent to the dead-letter office. Here it is
opened, and if it contains the name and address of the writer, the
letter is returned; but letters signed "Your loving Amy," "Your
devoted mother," "Your repentant son," fail to reach the eyes and
hearts of those who wait for them in vain. Last year 526,345
unclaimed letters written in foreign countries, probably to loved ones
in the United States, were sent to the dead-letter office. Think of the
heartaches which that means! Think of the loves and friendships
wrecked thereby!
Letters whose envelopes display the business card of the writer are
returned to the sender by the local postmaster after a certain period.
Papers, magazines, and books with insufficient postage are sent to
the dead-letter office, held for a short time, and then distributed to
hospitals, asylums, and penal institutions.
Wherever "Old Glory" floats, there the servants of Uncle Sam carry
his mail. Of this department every citizen should be proud, for its
speed and efficiency is equaled by no other mail service in the world.
XVIII
DEPARTMENT OF AGRICULTURE

bout fifty years ago, at the request of Hon. H. E.


Ellsworth, the sum of one thousand dollars was set
apart in the interest of agriculture; now there is a
Department of Agriculture, and its Secretary is a
member of the President's Cabinet.
The present Secretary of this department is Hon. James Wilson, of
Iowa. He served several terms in Congress, was Regent of the State
University of Iowa, and for six years prior to his present appointment
was Director of the Iowa Experimental Station and professor of
agriculture at the Iowa Agricultural College, Ames, Iowa.
The Department of Agriculture consists of twenty different divisions,
each one of which is worthy of a complete chapter. The department
has many buildings, but the main one stands within the grounds of
the Smithsonian Institution, in a bower of blooming plants and
clinging vines. Every kind of plant from the tropics to the Arctic
Circle which can be made to grow in this climate can be found in this
department.
Studies in ornamentation, best methods of grafting, pruning,
budding, hybridizing, and treating diseases of plants, trees, and
animals are thoroughly investigated at its experimental stations.
Vegetable and flower seeds, grass seeds, plants, trees, bulbs, and
grape-vines are distributed in the department through the Senators,
members, and delegates of Congress. By this means the best
varieties of the vegetable kingdom are carried throughout the United
States. During the coming year the country will be more carefully
districted, and only such seeds and plants as have been thoroughly
acclimated will be sent to the several districts.
Members of Congress from cities exchange their quota of vegetable
and crop seeds for flower seeds, thus leaving more of the former for
members with a farming constituency.
The following statement shows the amounts of seeds, bulbs, plants,
and trees, so far as the allotments have been made, for a recent
fiscal year:
Each Senator, member, and delegate will receive—
Vegetable Seed 12,000 packages, 5 papers each.
Novelties Vegetable 500 packages, 5 papers each.
Seed
Flower Seed 500 packages, 5 papers each.
Tobacco Seed 110 packages, 5 papers each to districts
growing tobacco.
Cotton Seed 70 packages, 1 peck each, to districts
growing cotton.
Lawn Grass Seed 30 packages.
Forage Crop Seed Allotment not yet made.
Sorghum Seed Allotment not yet made.
Sugar Beet Seed Allotment not yet made.
Bulbs 10 boxes, 35 bulbs each; or 20 boxes, 17
bulbs each.
Grape-vines 8 packages, 5 vines each.
Strawberry Plants 10 packages, 15 plants each.
Trees 20 packages, 5 trees each.
For seed distributed alone the government appropriates $270,000.
Think of the beneficence of that! The rarest and best seeds that
money can buy will be planted in every State and Territory of this
country. Experts are continually sent abroad to find new cereals,
fruits trees, animals, and flowers.
The department has at least one correspondent in every county of
the United States through whom the statistics on acreage, quality of
crops, and success of experiments are reported at stated times.
All questions pertaining to farming are answered by this department.
If a man desires to buy a farm in Kansas or Alaska, a portion of the
country of which he knows little, the department will tell him of the
climate, the crops likely to be remunerative, and the obstacles of soil
or climate to overcome. A chemist will analyze the soil for him, tell
him what it contains, and what it needs to produce certain crops. An
entomologist will tell him the insects prevalent which may destroy
his crops. The scientist will also tell him how to destroy the inserts,
what birds to encourage and what to banish.
At Summerville, S. C., the government has a tea farm with a fully
equipped factory, and the tea produced is claimed by experts to
equal the best imported article. This year one thousand acres of rice
land near Charleston, S. C., will be put in tea. The cost of producing
American tea is about fifteen cents a pound; the yield is four
hundred pounds to the acre, the wholesale selling price forty to fifty
cents per pound, and the retail price seventy-five cents to one dollar
per pound.
In the wheat-growing States the government is trying a fine variety
of macaroni wheat, in order to compete successfully with the
imported article, of which $8,000,000 worth enters this country
annually.
In the cotton States the government is trying Egyptian cotton, which
is now imported to the value of $8,000,000 annually.
In Arizona and other dry tracts dates and other Egyptian fruits are
being successfully acclimated. In the hot states rubber, coffee,
bananas, and cocoa are being tried.
Our fruit markets are being extended into Europe, and special
agents and consuls are using every influence to enlarge this market.
At the Paris Exposition our pears, apples, peaches, and plums were a
never-ending surprise to people of all lands. Californians made us all
proud of them by their lavish generosity, and the result has been
that pears and apples have been sent in large quantities to Southern
Europe, also to Russia and Siberia.
New cottons are being sent throughout the South, new prunes and
plums along the Pacific Coast. Important experiments are being
made in sugar producing. Pineapples are being acclimated in Florida,
plants which produce bay rum and various perfumes are being
introduced in several states, and olives from Italy are being tried in
Porto Rico and the Philippines.
In many different States soils have been examined. In Lancaster
County, Pennsylvania, it was found certain soils contain ingredients
to produce the finest Cuban tobacco, and other soil regarded as
useless was shown to be capable of producing certain rare plants.
Every state should call for this kind of analytic help, until we make
the United States the garden of the world.
XIX
DEPARTMENT OF CHEMISTRY ON PURE FOODS
DIETETICS
his subject of the relative value of foods is one that
interests every individual. The Department of Agriculture
is making a brave effort to secure a law regulating
interstate and international commerce, requiring that all
foods sent from one state to another, or to foreign
countries, shall be labeled for just what they are, and shall conform
to the government standard in excellence.
For instance, renovated or "process" butter is now passing its ordeal.
"Process" butter means that a large quantity of butter has been sent
to a factory or elsewhere, and there worked together and colored to
secure uniformity of appearance, and then placed on the market.
The government requires that it shall be properly labeled. It is of
less nutritive value than either oleomargarine or butterine. A
government leaflet gives householders and merchants full directions
for discovering the real value of anything called butter. Every farmer
should secure a copy of the Agricultural Year-book.
I remember once, a number of years ago, at a table in London,
discussing with some merchants from South America the subject of
buying their goods in the United States instead of England.
One man from British Guiana said: "It is impossible to deal with the
United States; they have no food-test laws, and we buy one thing
and get another. Then take machinery and implements. The first
three or four purchases will be all right, after which they put off on
us shelf-worn goods which they could not sell at home."
When the government can put an official stamp on each article
exported it will be good for the permanence of our export trade.
No such general law now exists, and the best our government can
do is to certify that the goods comply with the standard of the
country to which they are to be sent. It is believed that many of the
preservatives used with food products are harmless to the human
body, and a scientific test of this was conducted in December, 1902.
The Agricultural Department called upon the young scientists of the
colleges and universities to assist in settling this question. A picked
body of students were supplied with the purest food to bring them
to perfect condition, and soups, meats, vegetables, jellies, etc.,
containing preservatives claimed to be harmless will be given them,
and as soon as a touch of dyspepsia is manifest the test will be
dropped. It was doubtful whether football and baseball managers,
not to mention such insignificant factors as professors and mothers,
would consent that their favorites should be submitted to such
experiments. But scientists are earnest seekers for truth, and
enough subjects were readily found to make the trial.
It is not so much the making of impure foods that is objected to as it
is an effort to provide that goods shall be labeled for what they are—
that is, a can labeled raspberry jam shall not consist of gelatine with
a few raspberry seeds and juice used for coloring, but shall be the
real thing.
In recent testimony before Congress a case of this kind was brought
out. A certain firm made jelly from the refuse of apples—that is,
rotten and wilted apples, peelings and cores, stuff which when made
cost the firm one and a half cents a pound—and this they sold as
apple and currant jelly, selling hundreds of buckets. The government
forced the firm to label the buckets correctly, and the sale became
insignificant. Now, the poor need cheap foods, but it is not fair that
they should have to pay more than a thing is worth; besides, such
frauds interfere with the industry of the farmer's wife who sells pure
jelly.
The government now sends agents into every city, who buy from the
shelves of grocers just what they offer for sale. The grocer, of
course, does not recognize the government agent. The stuff is then
sent to the laboratory, and the grocer and manufacturer notified as
to results. The latter is told that his formula will be published, and
before that is done he will be permitted to offer any statement that
he may think advisable.
We are apt to think the "embalmed" meat agitation during the
Spanish war will injure the trade of the country more than the war
itself, but that agitation was right if it saved the health of even one
soldier, and, above all, if it secures society in the future against
deleterious canned meats.
It is well known, tho not approved by the government, that there
are several canneries in the West where horse-flesh only is used.
The government watches them closely and forces them to label the
goods for just what they are. These goods are sent to such foreign
countries as do not object to the use of horse-flesh.
Most States have stringent food laws, but so much food is sent from
the State in which it is produced to another that State laws become
inoperative.
The government finds glucose (not in itself harmful) to be the basis
of many frauds. Colored and flavored it is sold as honey, and it is the
foundation of very many jams. Cocoas and chocolates are made
from wheat, corn, rice, potatoes; pepper, cinnamon, allspice,
nutmegs, and mustards are made from almost every cereal. Pure
vinegar is rare. Almost any kind of wine can be drawn from the same
spigot, colored and flavored to suit the requirements of the wine
desired.
Sometimes in foreign lands I have thought that London particularly
needs a commission on pure coffee. I think I shall know the taste of
chicory as long as I live from experiences in that city.
Most foreign countries make stringent food laws chiefly on liquors
and butter. Germany draws close lines on meat, including all forms
of sausage, with some restrictions on butter, wine, coloring on toys,
and coloring matter generally.
Every European country has stringent laws on the composition of
beer. I wonder how long American beer which rots the shoes of the
bartender, and brings paralysis to his right hand, would be tolerated
in Germany or Britain? At the Buffalo Exposition, in the government
display, was one sample of "peach brandy," the formula of which
was forty gallons of proof spirits, one-half pound of an essence, one
quart of sugar syrup, and a sufficient amount of coloring matter. The
"bead oil" on the same shelf, it was claimed, was a solution of soap
intended to produce a "bead" on liquors, and thereby give the
appearance of age.
Could anything better prove the need of a government standard
than the above, or the further facts that one man is now in the
penitentiary for fraudulent use of the United States mail in
advertising ground soapstone as a flour adulterant, and that fifteen
cheaper oils are now used to adulterate pure olive oil?
If I were a young college woman I would go in for chemistry, and
make myself a food specialist for grocers, exporters, and importers. I
would make my home in some large institution where the food
question as to what nutriments the body needs, and what will
produce best results at the least cost, could be tested scientifically. I
would take the cook and her helpers into a loving partnership to
improve the dietetics of the establishment, and yet reduce expenses.
There is a new business now ready for earnest college women.
XX
DEPARTMENT OF THE INTERIOR

he Department of the Interior was created by act of


Congress in 1849. When the names of its subdivisions
are enumerated, it will readily be seen that no adequate
description of it can be given in one or two chapters.
It comprises the Patent Office, the Pension Office,
General Land Office, Bureau of Indian Affairs, Bureau of Education,
Commissioner of Railroads, and the Office of the Geological Survey.
Each office is managed by a commissioner or director, who has
under him a large force of officials and clerks.
In the chief building of the Department of the Interior, fronting on F
Street, and extending from Seventh to Ninth, and from F to G
Streets, may be found the Patent Office of the United States. No
other department so well reveals the inventive genius of the most
inventive people on earth.
Once at a table in Paris a Frenchman said to me: "The Americans
are inventors because they are lazy."
"Well," I said, "I have heard many surprising charges against my
countrymen, but that excels all. How do you make that out?"
"Well, I am a manufacturer. I set an American boy to keep a door
open; before half an hour he has invented a machine which will
open and shut it, and I find my boy playing marbles."
Photo by Clinedinst

THE PATENT OFFICE

"Sensible boy! Yes, with that view of it, maybe we are; we certainly
do not care to do by hand that which a machine can better
perform."
The Patent Office is one of the few departments which is more than
self-supporting. In the year 1836 but one patent was taken out;
during the year ending December 31, 1901, the total number of
applications was 46,449. The total receipts for the year were
$6,626,856.71; total expenditures, $1,297,385.64—leaving a balance
far over five million dollars in favor of the government.
There are divisions for different classes of inventions. When a patent
is applied for, examiners make all necessary investigations, and
carefully look into the invention claimed to be new, comparing it,
part by part, with patents already existing before determining
whether a patent can be granted. They have a library with plates
and descriptions of about everything under the sun. From this library
inventors can have books and plates sent them in order to compare
their work with inventions now existing.
The Secretary of the Interior is a member of the President's Cabinet,
and receives $12,000 per year. He has charge of the Capitol
(through the architect), the Insane Asylum, and the College for
Mutes—indeed, it would seem that his work is sufficient for ten
Secretaries.
There is an Assistant Secretary of the Interior, who receives $4,000
per annum, and commissioners of different divisions and bureaus
who receive from $3,000 to $6,000 annually.
Many officers of this department could command higher salaries in
the commercial world, but these positions secure honor and respect
not only for the man himself but also for his descendants, hence
these commissionerships are very desirable. For that reason men
give up a legal practise or a railroad position, bringing salaries eight
or ten times as large.
The present Secretary, Ethan Allen Hitchcock,[4] of Missouri, great-
grandson of Ethan Allen, of Vermont, has a wide experience in
manufacturing, railroad, and mining interests, and has served as
Ambassador to Russia. He was called to his present place in 1898.
4. Ethan Allen Hitchcock, Secretary of the Interior under Presidents McKinley
and Roosevelt, died April 9, 1909, age seventy-four.
The Secretary in his report for 1901 entreats that at least twenty
more persons of fine mechanical ability be appointed as examiners,
as his force is much behind in their work, altho many labor far over
allotted time.
The Bureau of Education, established in 1867, is probably as little
known to the general public as any branch of the government. It is a
clearing-house.
The Commissioner of Education, Hon. William T. Harris,[5] is one of
the great educators of the world. It is probable if the teachers of the
United States could have a personal vote, their unanimous choice
would fall upon Dr. Harris as their Commissioner. The offices of the
Bureau of Education are in a brick building at the corner of G and
Eighth Streets.
5. In July, 1906, Commissioner Harris retired on a Carnegie pension and Prof.
Elmer Ellsworth Brown, of California, became Commissioner of Education.
The Commissioner has about forty assistants, who are confined to
about twenty-eight rooms. This office collects, tabulates, and reports
on all schools in the United States. Any one who desires to compare
the curriculums of different institutions consults the Commissioner's
report. Or should one desire to know what is being done in Europe,
or any other part of the world, along the line of art in schools, or
manual or industrial training, or the advanced education for women,
all such inquiries can be answered by reference to the
Commissioner's report.
This bureau is held in high estimation in Europe. Many of the South
American republics and some Asiatic countries are trying, through
the reports of Dr. Harris, to model their school systems after that of
the United States.
Miss Frances G. French has charge of the foreign correspondence,
and tabulates statistics and reports on thirty-two foreign countries.
The school work presented by the Department of Education at Paris
in 1900 secured favorable commendation from the best educators of
Europe. Only three commissioners have preceded Dr. Harris: Hon.
Henry Barnard, 1867-1870; Hon. John Eaton, 1870-1886; Hon. N. H.
R. Dawson, 1886-1889. The latter was a brother-in-law of Abraham
Lincoln. Dr. Harris was appointed by President Harrison, September,
1889. The best work of the Bureau of Education lies in bringing
about homogeneity in the work of education throughout the United
States. Without the tabulated work of the Superintendents of States,
how would the Superintendent of, say, one of the Dakotas, know
whether the work of the public schools of his State corresponds with
the work done in New York or Pennsylvania? Yet the boy educated in
Dakota may have to do his life-work in Pennsylvania. Then the
Commissioner's report keeps us informed what the State, Nation, or
Church is doing for the education of the colored race, the Indian, or
the people of our new possessions.
A short extract from the Commissioner's report of 1899 will give an
idea of the tabulated work for women:
The barriers to woman's higher education seem effectually removed, and to-
day eight-tenths of the colleges, universities, and professional schools of the
United States are open to women students. As is stated by ex-President Alice
Freeman Palmer, of Wellesley College, "30,000 girls have graduated from
colleges, while 40,000 more are preparing to graduate." The obtaining of a
collegiate education gives the women more ambition to enter a profession, or,
if they decide to marry, it is stated that—
The advanced education they have received has added to their natural
endowments wisdom, strength, patience, balance, and self-control ... and
in addition to a wise discharge of their domestic duties, their homes have
become centers of scientific or literary study or of philanthropy in the
communities where they live.
It is stated that the advancement of women in professional life is less rapid
than in literature. The training of women for medical practise was long
opposed by medical schools and men physicians. Equally tedious was the
effort to obtain legal instruction and admission to the legal profession, and
even to-day the admission to theological schools and the ministry is seriously
contested; yet all these professions are gradually being opened to women. In
1896-97 there were in the United States 1,583 women pursuing medical
studies to 1,471 in 1895-96; in dentistry, 150 women in 1896-97 to 143 in
1895-96; in pharmacy, 131 in 1896-97 to 140 in 1895-96. In law courses of
professional schools were 131 women in 1896-97 to 77 in 1895-96; in
theological courses 193 women in 1896-97.
The only aggressive work done by this bureau is in Alaska, and of
this Dr. Sheldon Jackson[6] is agent or superintendent. Besides doing
a great work in education, this department has brought about 1,300
deer from Siberia to take the place of dogs, mules, and horses in
transportation, and at the same time to give milk, butter, cheese,
and meat to the population. The reindeer are self-supporting, living
on the moss which grows abundantly.
6. Dr. Sheldon Jackson died May 2, 1909.
These animals are loaned to individuals or missions, and at the end
of five years the government requires an equivalent number to be
returned. The Eskimo, the Lapp, and the Finn become expert in
handling these herds, now numbering many thousands. By them
mails are carried, and whalers, sealers, miners, and soldiers rescued
from starvation, danger, or death.
The education as well as religious training of Alaska is up to this time
conducted through the mission stations, all of which are visited,
encouraged, and assisted by Dr. Jackson.
The Youth's Companion tersely states the present condition of
things:
When the churches first planned to send missionaries and teachers into
Alaska, representatives of the several denominations met and divided the
territory among them. Should the traveler ask the ordinary Alaskan miner
what is the result of effort, he would probably be answered that there has
been no result. The miner, in the words of Dr. Sheldon Jackson, is
unconscious that the very fact of his presence there at all is the direct
outcome of Christian missions. In 1877 Sitka and St. Michaels were armed
trading-posts, out of which the soldiers shut the natives every night, that the
inhabitants might rest in safety. For ten years not a single whaler dared to
stay overnight at Cape Prince of Wales, so savage was the native population.
Now, in all those ports, the miner and whaler and traveler can dwell in safety,
because of the civilizing work of the missionaries. Probably ten thousand
natives have been brought under Christian influences, and many public as
well as mission schools have been opened.
Among the Moravian missions of the Yukon Valley few of the natives can read
or write. At bedtime a bell rings, and the entire population goes to the
churches. A chapter in the Bible is read, a prayer offered, a hymn sung; and
the men, women, and children return to their homes and go to bed. Where in
the United States can be found a better record?
In introducing religion with the arts, sciences, and conveniences of
civilization, Dr. Jackson's work reminds one of the words of Whittier:
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