Graphics Java 2D 1st Edition by Asura ISBN pdf download
Graphics Java 2D 1st Edition by Asura ISBN pdf download
download
https://ebookball.com/product/graphics-java-2d-1st-edition-by-
asura-isbn-13486/
https://ebookball.com/product/graphics-java-2d-1st-edition-by-
asura-isbn-13482/
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/
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/
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/
https://ebookball.com/product/idg-books-worldwide-1st-edition-by-
directx-3d-graphics-programming-bible-isbn-11082/
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
© 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
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
4 Chapter 12 Graphics and Java 2D™
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:
© 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
© 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:
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
8 Chapter 12 Graphics and Java 2D™
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
10 Chapter 12 Graphics and Java 2D™
© 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:
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 13
12.13 (Grid Using Method drawRect) Write an application that draws a 10-by-10 grid. Use the
Graphics method drawRect.
ANS:
© 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
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
16 Chapter 12 Graphics and Java 2D™
© 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
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 19
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:
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 23
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:
This creates an instance of class Timer that will call this object’s actionPerformed method every
1000 milliseconds (i.e., every second).
ANS:
© 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
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 25
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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
26 Chapter 12 Graphics and Java 2D™
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 27
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:
© 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
© 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:
© 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
© 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:
© 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
© 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
© 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:
© 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™
© 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
© 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:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Exercises 47
© 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
© 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.
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
50 Chapter 12 Graphics and Java 2D™
ANS:
© Copyright 1992-2007 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.
Another Random Scribd Document
with Unrelated Content
“Good going, Li,” Biff exclaimed. “And you described
Perez Soto?”
“We’ve got the boat, Biff. And it’s a real honey. As trim a
craft as you’d ever want to see.”
Biff then told his father and Mr. Mahenili what he and Li
had learned.
85
They peered intently at the yawl’s portholes
The boys secreted themselves. They peered intently at 86
the yawl’s portholes. There was barely enough light to
see.
87
CHAPTER XII
Bomb Away
Biff shook his head. “No. I don’t think so. You’d see
activity on the deck, too, and a truck somewhere
nearby. No, we’ve got to investigate what that character
is doing.”
“Well, look, you know how well I can swim under water. 88
Suppose I slip into the water on this side of the wharf.
Then I’ll swim under it, and I can come up right beside
the boat. I’ll move along from porthole to porthole and
see if I can find out what’s going on in the boat.”
The keg hurler was running along the deck toward the
boat’s bow. Here he could leap on the dock and make
his getaway.
Biff rubbed the small of his back with his left hand.
“That hurt. And here you are laughing at me.”
Biff ran to where his father stood. It may have been all
right, but Biff could tell by the beads of perspiration
standing out on his father’s forehead and by his soaked
shirt, that it had been a ticklish job.
“How, Dad?”
“Well, Perez Soto would know that we’d use the engine
to get us out of the harbor. Maybe a twenty-minute run.
Then we’d go to sail. And we’d use sail every minute we
could. But then—this is the really devilish clever part of
his plan.” Mr. Brewster paused. He turned to Li’s father.
“You bet there are,” Mr. Mahenili said. “And the water’s
shark-infested, too.”
97
CHAPTER XIII
A Near Miss
“Aye, aye, sir,” Biff called back to his father. Biff held on
to the bow line, loosely circled over a piling at the dock.
Biff came into the cockpit and took the tiller over from
his father.
“It’s the greatest. I’ll take sail over power any day.” Li
spoke as if he were an old salt.
The boys were quiet. The spell of the night settled over
them. Li, Biff knew, dozed off from time to time. He
himself felt drowsy, lulled into sleepiness by the slight
rise and fall of the craft as it rode over the swells.
“All right, boys. We’ll take over now. Get some sleep. At
this steady pace, we’ll reach Upolu long before daylight.
We’ll drop anchor, then set out again at daybreak.”
Biff and Li had their work cut out for them. The course 101
set was a zigzag one. They wanted to cruise as much of
the coastline as possible in the hope of spotting some
sign of Huntington’s sunken sloop.
Biff would head the Easy Action off shore, run out
nearly ten miles, then tack back in. For every three
miles they progressed down the coast toward Ka Lae,
the southern tip of Hawaii, they covered nearly twenty
miles out and back from the coast.
The next morning the search was continued, the yawl 102
weaving its way in and out along the coast, drawing
nearer to Ka Lae, nearer to the position at which
Huntington had last been heard from.
“I’ll take the tiller now, Biff,’” his father said. “Hank and I
will alternate. I want you and Li to keep a constant
watch. Your young eyes are sharper than ours.”
The Easy Action spent the day crisscrossing a wide area
of water between the shore line and a distance outside
the coral shoals, varying from five to twelve miles.
“What about Dr. Weber?” Biff asked. “Do you think he’s
aboard Perez Soto’s boat, or do you think he’s being
held on shore?”
“Me, Dad.” Biff jumped at the chance. “I’d love to. Nice
warm night. The sleeping will be better under the stars
than it will be in the cabin.”
Biff raised a cry. It was too late. His voice was drowned
out by the roar of the cruiser’s engines—Biff knew now
that it was a twin-engined craft.
Now the boat seemed on top of the yawl. Its bow, with
a much higher freeboard than the low-lying yawl, reared
up menacingly only twenty feet from the sailing craft.
Surely it would crash them, ram them, send them to the
bottom of the sea, with Biff’s father, Hank Mahenili, and
Li trapped below.
Biff yelled.
Biff went into action. Maybe he could start the engine 106
before the water did its damage. He splashed through
the water and reached the engine compartment. He
pulled open the door. It had held back the flood from
the engine room. Before the water could rush in and fill
up that compartment, Biff had the engine going. He
quickly turned on the yawl’s sea pumps. He stood there
with his fingers crossed, hoping the engine wouldn’t
conk out. It didn’t. The heavy-duty pumps worked
perfectly. Already the water inside the boat was
beginning to recede.
ebookball.com