SE450: Compound Shapes [40/65] |
GeneralPath path = new GeneralPath();
path.append(new Rectangle(...), false);
path.append(new Triangle(...), false);
g2.draw(path);
file:horstmann/ch06_scene3/CompoundShape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package horstmann.ch06_scene3; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import java.awt.geom.Point2D; /** A scene shape that is composed of multiple geometric shapes. */ public abstract class CompoundShape extends SelectableShape { public CompoundShape() { path = new GeneralPath(); } protected void add(Shape s) { path.append(s, false); } public boolean contains(Point2D aPoint) { return path.contains(aPoint); } public void translate(int dx, int dy) { path.transform( AffineTransform.getTranslateInstance(dx, dy)); } public void draw(Graphics2D g2) { g2.draw(path); } private GeneralPath path; }
file:horstmann/ch06_scene3/HouseShape.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package horstmann.ch06_scene3; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** A house shape. */ public class HouseShape extends CompoundShape { /** Constructs a house shape. @param x the left of the bounding rectangle @param y the top of the bounding rectangle @param width the width of the bounding rectangle */ public HouseShape(int x, int y, int width) { Rectangle2D.Double base = new Rectangle2D.Double(x, y + width, width, width); // The left bottom of the roof Point2D.Double r1 = new Point2D.Double(x, y + width); // The top of the roof Point2D.Double r2 = new Point2D.Double(x + width / 2, y); // The right bottom of the roof Point2D.Double r3 = new Point2D.Double(x + width, y + width); Line2D.Double roofLeft = new Line2D.Double(r1, r2); Line2D.Double roofRight = new Line2D.Double(r2, r3); add(base); add(roofLeft); add(roofRight); } }