Java Reference
In-Depth Information
To create a happy face, we'll touch up the mouth. Line 26 sets the color to
Color.YELLOW , so any shapes we draw will blend in with the face. Line 27 draws a rectangle
that's half the mouth's height. This erases the top half of the mouth, leaving just the
bottom half. To create a better smile, line 28 draws another oval to slightly cover the upper
portion of the mouth. Class DrawSmileyTest (Fig. 6.12) creates and displays a JFrame
containing the drawing. When the JFrame is displayed, the system calls method paint-
Component to draw the smiley face.
1
// Fig. 6.12: DrawSmileyTest.java
2
// Test application that displays a smiley face.
3
import javax.swing.JFrame;
4
5
public class DrawSmileyTest
6
{
7
public static void main(String[] args)
8
{
9
DrawSmiley panel = new DrawSmiley();
10
JFrame application = new JFrame();
11
12
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
13
application.add(panel);
14
application.setSize( 230 , 250 );
15
application.setVisible( true );
16
}
17
} // end class DrawSmileyTest
Fig. 6.12 | Test application that displays a smiley face.
GUI and Graphics Case Study Exercises
6.1 Using method fillOval , draw a bull's-eye that alternates between two random colors, as in
Fig. 6.13. Use the constructor Color(int r, int g, int b ) with random arguments to generate ran-
dom colors.
6.2 Create a program that draws 10 random filled shapes in random colors, positions and sizes
(Fig. 6.14). Method paintComponent should contain a loop that iterates 10 times. In each iteration,
the loop should determine whether to draw a filled rectangle or an oval, create a random color and
choose coordinates and dimensions at random. The coordinates should be chosen based on the pan-
el's width and height. Lengths of sides should be limited to half the width or height of the window.
 
Search WWH ::




Custom Search