Java Reference
In-Depth Information
The code to draw this diamond would be the following:
g.drawRect(78, 22, 50, 50);
g.drawLine(78, 47, 103, 22);
g.drawLine(103, 22, 128, 47);
g.drawLine(128, 47, 103, 72);
g.drawLine(103, 72, 78, 47);
As you can see, the parameter values passed to the drawRect and drawLine meth-
ods are very similar to those of the first diamond, except that they're shifted by 78 in
the x -direction and 22 in the y -direction (except for the third and fourth parameters to
drawRect , since these are the rectangle's width and height). This (78, 22) shift is
called an offset.
We can generalize the coordinates to pass to Graphics g 's drawing commands so
that they'll work with any diamond if we pass that diamond's top-left x - and y -offset.
For example, we'll generalize the line from (0, 25) to (25, 0) in the first diamond and
from (78, 47) to (103, 22) in the second diamond by saying that it is a line from
( x , y
25, y ), where ( x , y ) is the offset of the given diamond.
The following program uses the drawDiamond method to draw three diamonds
without redundancy:
25) to ( x
1 // This program draws several diamond figures of size 50x50.
2
3 import java.awt.*;
4
5 public class DrawDiamonds {
6
public static void main(String[] args) {
7
DrawingPanel panel = new DrawingPanel(250, 150);
8
Graphics g = panel.getGraphics();
9
10
drawDiamond(g, 0, 0);
11
drawDiamond(g, 78, 22);
12
drawDiamond(g, 19, 81);
13
}
14
15
// draws a diamond in a 50x50 box
16
public static void drawDiamond(Graphics g, int x, int y) {
17
g.drawRect(x, y, 50, 50);
18
g.drawLine(x, y + 25, x + 25, y);
19
g.drawLine(x + 25, y, x + 50, y + 25);
20
g.drawLine(x + 50, y + 25, x + 25, y + 50);
21
g.drawLine(x + 25, y + 50, x, y + 25);
22
}
23 }
 
Search WWH ::




Custom Search