Java Reference
In-Depth Information
•s e
if statement (selection)
while statement (repetition)
and that these can be combined in only two ways— stacking and nesting . Indeed, structured
programming is the essence of simplicity.
5.11 (Optional) GUI and Graphics Case Study: Drawing
Rectangles and Ovals
This section demonstrates drawing rectangles and ovals, using the Graphics methods
drawRect and drawOval , respectively. These methods are demonstrated in Fig. 5.27.
1
// Fig. 5.27: Shapes.java
2
// Drawing a cascade of shapes based on the user's choice.
3
import java.awt.Graphics;
4
import javax.swing.JPanel;
5
6
public class Shapes extends JPanel
7
{
8
private int choice; // user's choice of which shape to draw
9
10
// constructor sets the user's choice
11
public Shapes( int userChoice)
12
{
13
choice = userChoice;
14
}
15
16
// draws a cascade of shapes starting from the top-left corner
17
public void paintComponent(Graphics g)
18
{
19
super .paintComponent(g);
20
21
for ( int i = 0 ; i < 10 ; i++)
22
{
23
// pick the shape based on the user's choice
24
switch (choice)
25
{
26
case 1 : // draw rectangles
27
g.drawRect( 10 + i * 10 , 10 + i * 10 ,
50 + i * 10 , 50 + i * 10 );
28
29
break ;
30
case 2 : // draw ovals
31
g.drawOval( 10 + i * 10 , 10 + i * 10 ,
50 + i * 10 , 50 + i * 10 );
32
33
break ;
34
}
35
}
36
}
37
} // end class Shapes
Fig. 5.27 | Drawing a cascade of shapes based on the user's choice.
 
 
Search WWH ::




Custom Search