Java Reference
In-Depth Information
Graphics methods fillRect and fillOval draw filled rectangles and ovals, respec-
tively. These have the same parameters as drawRect and drawOval ; the first two are the
coordinates for the upper-left corner of the shape, while the next two determine the width
and height . The example in Figs. 6.11-6.12 demonstrates colors and filled shapes by
drawing and displaying a yellow smiley face on the screen.
1
// Fig. 6.11: DrawSmiley.java
2
// Drawing a smiley face using colors and filled shapes.
3
4
import java.awt.Color;
import java.awt.Graphics;
5
import javax.swing.JPanel;
6
7
public class DrawSmiley extends JPanel
8
{
9
public void paintComponent(Graphics g)
10
{
11
super .paintComponent(g);
12
13
// draw the face
14
g.setColor( Color.YELLOW );
g.fillOval( 10 , 10 , 200 , 200 );
15
16
17
// draw the eyes
18
g.setColor( Color.BLACK );
g.fillOval( 55 , 65 , 30 , 30 );
g.fillOval( 135 , 65 , 30 , 30 );
19
20
21
22
// draw the mouth
23
g.fillOval( 50 , 110 , 120 , 60 );
24
25
// "touch up" the mouth into a smile
26
g.setColor( Color.YELLOW );
g.fillRect( 50 , 110 , 120 , 30 );
g.fillOval( 50 , 120 , 120 , 40 );
27
28
29
}
30
} // end class DrawSmiley
Fig. 6.11 | Drawing a smiley face using colors and filled shapes.
The import statements in lines 3-5 of Fig. 6.11 import classes Color , Graphics and
JPanel . Class DrawSmiley (lines 7-30) uses class Color to specify drawing colors, and uses
class Graphics to draw.
Class JPanel again provides the area in which we draw. Line 14 in method paint-
Component uses Graphics method setColor to set the current drawing color to
Color.YELLOW . Method setColor requires one argument, the Color to set as the drawing
color. In this case, we use the predefined object Color.YELLOW .
Line 15 draws a circle with diameter 200 to represent the face—when the width and
height arguments are identical, method fillOval draws a circle. Next, line 18 sets the
color to Color.Black , and lines 19-20 draw the eyes. Line 23 draws the mouth as an oval,
but this is not quite what we want.
 
Search WWH ::




Custom Search