Exercises

Included below are short-answer and programming exercises. Answers are provided for those exercises whose exercise number is a hyperlink. Because college faculty use these exercises in their exams, we have provided answers to roughly half of the exercises included here.


11.4 Fill in the blanks in each of the following:
  1. Class ________ of the Java2D API is used to define ovals.
  2. Methods draw and fill of class Graphics2D require an object of type ________ as their argument.
  3. The three constants that specify font style are ________, ________ and ________.
  4. Graphics2D method ________ sets the painting color for Java2D shapes.

11.5 State whether each of the following is true or false. If false, explain why.

  1. The drawPolygon method automatically connects the endpoints of the polygon.
  2. The drawLine method draws a line between two points.
  3. The fillArc method uses degrees to specify the angle.
  4. In the Java coordinate system, y values increase from top to bottom.
  5. The Graphics class inherits directly from class Object.
  6. The Graphics class is an abstract class.
  7. The Font class inherits directly from class Graphics.

11.6 Write a program that draws a series of eight concentric circles. The circles should be separated by 10 pixels. Use the drawOval method of class Graphics.

11.7 Write a program that draws a series of eight concentric circles. The circles should be separated by 10 pixels. Use the drawArc method.

11.8 Modify your solution to Exercise 11.6 to draw the ovals using instances of class Ellipse2D.Double and method draw of class Graphics2D.

11.9 Write a program that draws lines of random lengths in random colors.

11.10 Modify your solution to Exercise 11.9 to draw random lines, in random colors and random line thicknesses. Use class Line2D.Double and method draw of class Graphics2D to draw the lines.

11.11 Write a program that displays randomly generated triangles in different colors. Each triangle should be filled with a different color. Use class GeneralPath and method fill of class Graphics2D to draw the triangles.

11.12 Write a program that randomly draws characters in different font sizes and colors.

11.13 Write a program that draws an 8-by-8 grid. Use the drawLine method.

11.14 Modify your solution to Exercise 11.13 to draw the grid using instances of class Line2D.Double and method draw of class Graphics2D.

11.15 Write a program that draws a 10-by-10 grid. Use the drawRect method.

11.16 Modify your solution to Exercise 11.15 to draw the grid using instances of class Rectangle2D.Double and method draw of class Graphics2D.

11.17 Write a program that draws a tetrahedron (a pyramid). Use class GeneralPath and method draw of class Graphics2D.

11.18 Write a program that draws a cube. Use class GeneralPath and method draw of class Graphics2D.

11.19 In Exercise 3.9, you wrote an applet that input the radius of a circle from the user and displayed the circle's diameter, circumference and area. Modify your solution to Exercise 3.9 to read 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.Double object to represent the circle and method draw of class Graphics2D to display the circle.

11.20 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 application 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 paint. Do you notice any problems with this on your system?

11.21 Here is a peek ahead. 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 11.20 to remove the call to repaint from method paint. Define your class so it implements ActionListener (the actionPerformed method should simply call repaint). Define 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).

11.22 Modify your solution to Exercise 11.21 to enable 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. Note: Combining Swing GUI components and drawing leads to interesting problems for which we present solutions in Chapters 12 and 13. For now, the first line of your paint method should be

super.paint( g )

to ensure that the GUI components are displayed properly. You will notice that some of the randomly drawn lines will obscure the JTextField. Use an inner class definition to perform event handling for the JTextField.

11.23 Modify your solution to Exercise 11.21 to randomly choose different shapes to display (use methods of class Graphics).]

11.24 Modify your solution to Exercise 11.23 to use classes and drawing capabilities of the Java2D API. For shapes such as rectangles and ellipses, draw them with randomly generated gradients (use class GradientPaint to generate the gradient).

11.25 Write a graphical version of your solution to Exercise 6.37-the Towers of Hanoi. After studying Chapter 16, you will be able to implement a version of this exercise using Java’s image, animation and audio capabilities.

11.26 Modify the die-rolling program of Fig. 7.9 so that it updates the counts for each side of the die after each roll. Convert the application into a windowed application (i.e., a subclass of JFrame) and use Graphics method drawString to output the totals.

11.27 Modify your solution to Exercise 7.21-Turtle Graphics-to add a graphical user interface using JTextFields and JButtons. Also, draw lines rather than drawing 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 Java2D API features. [Note: Combining Swing GUI components and drawing leads to interesting problems for which we present solutions in Chapters 12 and 13. For now, the first line of your paint method should be

super.paint( g )

to ensure that the GUI components are displayed properly.]

11.28 Produce a graphical version of the Knight's Tour problem (Exercises 7.22, 7.23 and 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 would like, use class Timer (see Exercise 11.24) to help animate the Knight's Tour. Every second, the next move should be made.

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

11.30 Produce a graphical version of the Maze Traversal problem (Exercises 7.38-7.40). Use the mazes you produced as guides for creating the graphical versions. While the maze is being solved, a small circle should be displayed in the maze indicating the current position. If you would like, use class Timer (see Exercise 11.24) to help animate the traversal of the maze. Every second, the next move should be made.

11.31 Produce a graphical version of the Bucket Sort (Exercise 7.28) that shows each value being placed into the appropriate bucket and eventually being copied back to the original array.

11.32 Write a program that uses method drawPolyline to draw a spiral.

11.33 Write a program that inputs four numbers and graphs the numbers as a pie chart. Use class Arc2D.Double and method fill of class Graphics2D to perform the drawing. Draw each piece of the pie in a separate color.

11.34 Write an applet that inputs four numbers and graphs the numbers as a bar graph. Use class Rectangle2D.Double and method fill of class Graphics2D to perform the drawing. Draw each bar in a separate color.


Selected Answers

Included below are answers to approximately half the of the exercises in the Cyber Classroom. We are not able to include answers to every exercise because college faculty use these exercises in their classroom exams.


11.4 Fill in the blanks in each of the following:

  1. Class of the Java2D API is used to define ovals.
    ANS: Ellipse2D.
  2. Methods draw and fill of class Graphics2D require an object of type as their argument.
    ANS: Shape.
  3. The three constants that specify font style are , and .
    ANS: Font.PLAIN, Font.BOLD and Font.ITALIC.
  4. Graphics2D method sets the painting color for Java2D shapes.
    ANS: setColor.

11.5 State whether each of the following is true or false. If false, explain why.

  1. The drawPolygon method automatically connects the endpoints of the polygon.
    ANS: True.
  2. The drawLine method draws a line between two points.
    ANS: True.
  3. The fillArc method uses degrees to specify the angle.
    ANS: True.
  4. In the Java coordinate system, y values increase from top to bottom.
    ANS: False. In the Java coordinate system, y values increase from top to bottom.
  5. The Graphics class inherits directly from class Object.
    ANS: True.
  6. The Graphics class is an abstract class.
    ANS: True.
  7. The Font class inherits directly from class Graphics.
    ANS: False. Class Font inherits directly from class Object.

11.6

// Exercise 11.6 Solution
// Concentric.java
// This program draws concentric circles
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Concentric extends JFrame {

   public Concentric()
   {
      super( "Concentric" );
      setSize( 300, 300 );
      show();
   }

   public void paint( Graphics g )
   {
      for ( int x = 0; x <= 160; x += 10 ) {
         int y = 160 - ( x * 2 );
         g.drawOval( x + 30, x + 30, y, y );
      }
   }

   public static void main( String args[] )
   {
      Concentric app = new Concentric();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );      
   }
}

11.12

// Exercise 11.12 Solution
// Lines1.java
// This program draws lines of random sizes and colors
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Lines1 extends JFrame {

   public Lines1()
   {
      super( "Drawing Lines" );
      setSize( 200, 200 );
      show();
   }

   public void paint( Graphics g )
   {
      for ( int y = 10; y < 200; y += 10 ) {
         int x1 = ( int ) ( 1 + Math.random() * 199 );
         g.setColor( new Color( ( float ) Math.random(), 
            ( float ) Math.random(), ( float ) Math.random() ) );
         g.drawLine( 1, y, x1, y );  
      }
   }
   
   public static void main( String args[] )
   {
      Lines1 app = new Lines1();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );      
   }

}

11.15

// Exercise 11.15 Solution
// Draw.java
// This program randomly draws characters
// Note: cover, resize, or restart the program
// repeatedly to see multiple characters drawn
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Draw extends JFrame {
   private final int DELAY = 3000000;

   public Draw()
   {
      super( "Drawing Characters" );
      setSize( 200, 200 );
      show();
   }  

   public void paint( Graphics g )
   {
      int fontSize = ( int ) ( 10 + Math.random() * 63 );
      int x = ( int ) ( 30 + Math.random() * 341 );
      int y = ( int ) ( 50 + Math.random() * 95 );
      char letters[] = { 'V', 'O', 'L', 'S', '8', '7' };
      Font f = new Font( "Monospaced", Font.BOLD, fontSize );

      g.setColor( new Color( ( float ) Math.random(), 
                             ( float ) Math.random(),
                             ( float ) Math.random() ) );
      g.setFont( f );
      g.drawChars( letters, ( int ) ( Math.random() * 6 ), 1, x, y );

      for ( int h = 1; h < DELAY; h++ ) ;  // slow things down
      repaint();
   }

   public static void main( String args[] )
   {
      Draw app = new Draw();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );      
   }
}

11.16

// Exercise 11.16 Solution
// Grid.java
// This program draws an 8 x 8 grid
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Grid extends JFrame {
   public Grid()
   {
      super( "Grid" );
      setSize( 200, 200 );
      show();
   }
   public void paint( Graphics g )
   {
      int y = 30, x1 = 30;

      for ( int r = 1; r <= 8; r++, y += 10 ) 
         g.drawLine( 30, y, 100, y );

      for ( int c = 1; c <= 8; c++, x1 += 10 )
         g.drawLine( x1, 30, x1, 100 );
   }

   public static void main( String args[] )
   {
      Grid app = new Grid();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );      
   }
}

11.20

// Exercise 11.20 Solution
// Pyramid.java
// This program draws a tetrahedron
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

public class Pyramid extends JFrame {

   public Pyramid()
   {
      super( "Pyramid" );
      setSize( 275, 150 );
      show();
   }

   public void paint( Graphics g )
   {
      int basex[] = { 100, 200, 150, 50, 100 };
      int basey[] = { 100, 100, 130, 130, 100 };
      int x = 110, y = 40;

      Graphics2D g2d = ( Graphics2D ) g;

      GeneralPath tetra = new GeneralPath();

      g2d.setColor( Color.red );
      
      tetra.moveTo( basex[ 0 ], basey[ 0 ] );

      for ( int i = 1; i < 5; i++ ) {
         tetra.lineTo( x, y );
         tetra.moveTo( basex[ i - 1 ], basey[ i - 1 ] );
         tetra.lineTo( basex[ i ], basey[ i ] );
      }

      tetra.closePath();
      g2d.draw( tetra ); 
   }

   public static void main( String args[] )
   {
      Pyramid app = new Pyramid();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );
   }
}

11.29

// Exercise 11.29 Solution
// RollDie.java
// Roll a six-sided die 6000 times
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import java.awt.*;

public class RollDie extends JFrame {

   public RollDie()
   {
      super( "Roll Die" );
      setSize( 275, 150 );
      show();
   }

   public void paint( Graphics g )
   {
      int yPosition = 50, face;
      int frequency[] = new int[ 7 ];
      Random r = new Random();

      for ( int roll = 1 ; roll <= 6000; roll++ ) {
         face = 1 + Math.abs( r.nextInt() % 6 );
         ++frequency[ face ];
      }
       
      g.setColor( Color.white );
      g.fillRect( 0, 0, 275, 150 );   // 275 x 150
      g.setColor( Color.black );
      g.drawString( "Face", 25, yPosition );
      g.drawString( "Frequency", 100, yPosition );

      for ( int i = 1; i < frequency.length; i++ ) {
         yPosition += 15;
         g.drawString( String.valueOf( i ), 25, yPosition );
         g.drawString( String.valueOf( frequency[ i ] ),
                       100, yPosition );
      }
   }

   public static void main( String args[] )
   {
      RollDie app = new RollDie();
      app.addWindowListener(
         new WindowAdapter() {
            public void windowClosing( WindowEvent e )
            {
               System.exit( 0 );
            }
         }
      );      
   }
}