Exercises

  • Exercise 12-1. Example 12-1 contains a centerText( ) method that centers one or two lines of text within a rectangle. Write a modified version of this method that positions a single line of text according to two new method parameters. One parameter should specify the horizontal positioning: left-, center-, or right-justified. The other parameter should specify the vertical position: at the top of the rectangle, centered, or at the bottom of the rectangle. You can use the FontMetrics class, as Example 12-1 does, or the Java 2D getStringBounds( ) method of the Font class. Write a GraphicsExample class that demonstrates all nine possible positioning types supported by your method.

  • Exercise 12-2. Use the animation techniques demonstrated in this chapter to write an applet that scrolls a textual message across the screen. The text to scroll and the scrolling speed should be read from applet parameters specified with <PARAM> tags in an HTML file.

  • Exercise 12-3. Experiment with the graphics capabilities of the Graphics and Graphics2D classes, and write an applet or application that displays some kind of interesting and dynamic graphics. You may want to take your inspiration from one of the many screensaver programs on the market. For example, you might draw filled rectangles on the screen, using random sizes, positions, and colors. (See Math.random( ) and java.util.Random for ways to generate random numbers.) Feel free to use any of the custom Shape, Stroke, or Paint classes developed ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.