Wrap-Up

Answers to Self Review Exercises

12.1

a) setStroke, Graphics2D. b) GradientPaint. c) drawLine. d) red, green, blue. e) points. f) TexturePaint.

12.2
  1. False. The first two arguments specify the upper-left corner of the bounding rectangle.
  2. True.
  3. True.
  4. True.
  5. False. Font sizes are measured in points.
  6. False. The coordinate (0,0) corresponds to the upper-left corner of a GUI component on which drawing occurs.
12.3
  1. The setFont method takes a Font object as an argumentnot a String.
  2. The Graphics class does not have an erase method. The clearRect method should be used.
  3. Font.BOLDITALIC is not a valid font style. To get a bold italic font, use Font.BOLD + Font.ITALIC.
  4. 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:

  1. Class _____ of the Java 2D API is used to draw 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 Java 2D shapes.
12.5

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

  1. Graphics method drawPolygon automatically connects the endpoints of the polygon.
  2. Graphics method drawLine draws a line between two points.
  3. Graphics method fillArc uses degrees to specify the angle.
  4. In the Java coordinate system, values on the y-axis increase from left to right.
  5. Graphics inherits directly from class Object.
  6. Graphics is an abstract class.
  7. The Font class inherits directly from class Graphics.
 
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.

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.

12.8

(Random Lines Using Class Line2D.Double) Modify your solution to Exercise 12.7 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.

12.9

(Random Triangles) Write an application 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.

12.10

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

12.11

(Grid Using Method drawLine) Write an application that draws an 8-by-8 grid. Use Graphics method drawLine.

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.

12.13

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

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.

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.

12.16

(Drawing Cubes) Write an application that draws a cube. Use class GeneralPath and method draw of class Graphics2D.

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 p. [ Note: You may also use the predefined constant Math.PI for the value of p. 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):

 

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.Double object to represent the circle and method draw of class Graphics2D to display the circle.

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

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).

12.20

(Screen Saver for a Random Number of Lines) Modify your solution to Exercise 12.19 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. Use an inner class to perform event handling for the JTextField.

12.21

(Screen Saver with Shapes) Modify your solution to Exercise 12.19 such that it uses randomnumber generation to choose different shapes to display. Use methods of class Graphics.

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.

12.23

(Turtle Graphics) Modify your solution to Exercise 7.21Turtle Graphicsto add a graphical 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.

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.

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.]

 
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.

Figure 12.33. Spiral drawn using method drawPolyline.

(This item is displayed on page 635 in the print version)

12.27

(Pie Chart) Write a program that inputs four numbers and graphs them 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.

12.28

(Selecting Shapes) Write an application that allows the user to select a shape from a JComboBox and draws it 20 times with random locations and dimensions in method paintComponent. The first item in the JComboBox should be the default shape that is displayed the first time paintComponent is called.

12.29

(Random Colors) Modify Exercise 12.28 to draw each of the 20 randomly sized shapes in a randomly selected color. Use all 13 predefined Color objects in an array of Colors.

12.30

(JColorChooser Dialog) Modify Exercise 12.28 to allow the user to select the color in which shapes should be drawn from a JColorChooser dialog.

(Optional) GUI and Graphics Case Study: Adding Java2D

12.31

Java2D introduces many new capabilities for creating unique and impressive graphics. We will add a small subset of these features to the drawing application you created in Exercise 11.18. In this version of the drawing application, you will enable the user to specify gradients for filling shapes and to change stroke characteristics for drawing lines and outlines of shapes. The user will be able to choose which colors compose the gradient and set the width and dash length of the stroke.

First, you must update the MyShape hierarchy to support Java2D functionality. Make the following changes in class MyShape:

  1. Change abstract method draw's parameter type from Graphics to Graphics2D.
  2. Change all variables of type Color to type Paint to enable support for gradients. [Note: Recall that class Color implements interface Paint.]
  3. Add an instance variable of type Stroke in class MyShape and a Stroke parameter in the constructor to initialize the new instance variable. The default stroke should be an instance of class BasicStroke.

Classes MyLine, MyBoundedShape, MyOval and MyRect should each add a Stroke parameter to their constructors. In the draw methods, each shape should set the Paint and the Stroke before drawing or filling a shape. Since Graphics2D is a subclass of Graphics, we can continue to use Graphics methods drawLine, drawOval, fillOval, etc. to draw the shapes. When these methods are called, they will draw the appropriate shape using the specified Paint and Stroke settings.

Next, you will update the DrawPanel to handle the Java2D features. Change all Color variables to Paint variables. Declare an instance variable currentStroke of type Stroke and provide a set method for it. Update the calls to the individual shape constructors to include the Paint and Stroke arguments. In method paintComponent, cast the Graphics reference to type Graphics2D and use the Graphics2D reference in each call to MyShape method draw.

Next, make the new Java2D features accessible from the GUI. Create a JPanel of GUI components for setting the Java2D options. Add these components at the top of the DrawFrame below the panel that currently contains the standard shape controls (see Fig. 12.34). These GUI components should include:

  1. A check box to specify whether to paint using a gradient
  2. Two JButtons that each show a JColorChooser dialog to allow the user to choose the first and second color in the gradient. (These will replace the JComboBox used for choosing the color in Exercise 11.18.)
  3. A text field for entering the Stroke width
  4. A text field for entering the Stroke dash length
  5. A check box for selecting whether to draw a dashed or solid line

Figure 12.34. Drawing with Java2D.

 

If the user selects to draw with a gradient, set the Paint on the DrawPanel to be a gradient of the two colors chosen by the user. The expression

 new GradientPaint( 0, 0, color1, 50, 50, color2, true ) )
 

creates a GradientPaint that cycles diagonally from the upper-left to the bottom-right every 50 pixels. Variables color1 and color2 represent the colors chosen by the user. If the user does not select to use a gradient, then simply set the Paint on the DrawPanel to be the first Color chosen by the user.

For strokes, if the user chooses a solid line, then create the Stroke with the expression

 new BasicStroke( width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND )
 

where variable width is the width specified by the user in the line-width text field. If the user chooses a dashed line, then create the Stroke with the expression

 new BasicStroke( width, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
 10, dashes, 0 )
 

where width again is the width in the line-width field, and dashes is an array with one element whose value is the length specified in the dash-length field. The Panel and Stroke objects should be passed to the shape object's constructor when the shape is created in DrawPanel.

Introduction to Computers, the Internet and the World Wide Web

Introduction to Java Applications

Introduction to Classes and Objects

Control Statements: Part I

Control Statements: Part 2

Methods: A Deeper Look

Arrays

Classes and Objects: A Deeper Look

Object-Oriented Programming: Inheritance

Object-Oriented Programming: Polymorphism

GUI Components: Part 1

Graphics and Java 2D™

Exception Handling

Files and Streams

Recursion

Searching and Sorting

Data Structures

Generics

Collections

Introduction to Java Applets

Multimedia: Applets and Applications

GUI Components: Part 2

Multithreading

Networking

Accessing Databases with JDBC

Servlets

JavaServer Pages (JSP)

Formatted Output

Strings, Characters and Regular Expressions

Appendix A. Operator Precedence Chart

Appendix B. ASCII Character Set

Appendix C. Keywords and Reserved Words

Appendix D. Primitive Types

Appendix E. (On CD) Number Systems

Appendix F. (On CD) Unicode®

Appendix G. Using the Java API Documentation

Appendix H. (On CD) Creating Documentation with javadoc

Appendix I. (On CD) Bit Manipulation

Appendix J. (On CD) ATM Case Study Code

Appendix K. (On CD) Labeled break and continue Statements

Appendix L. (On CD) UML 2: Additional Diagram Types

Appendix M. (On CD) Design Patterns

Appendix N. Using the Debugger

Inside Back Cover



Java(c) How to Program
Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net