1 /* 2 * File: TriangleTest2.java 3 * 4 * Drawing triangles (an exercise) 5 * 6 * Copyright: Northeast Parallel Architectures Center 7 * 8 */ 9 10 import java.applet.Applet; 11 import java.awt.Graphics; 12 import java.awt.Polygon; 13 import java.awt.Color; 14 15 public class TriangleTest2 extends Applet { 16 17 // create references to three triangles: 18 private Triangle triangle1, triangle2, triangle3; 19 20 public void init() { 21 22 // instantiate an isosceles triangle: 23 triangle1 = new Triangle( 50, 25, 75, 100, 25, 100 ); 24 // instantiate a right triangle: 25 triangle2 = new Triangle( 125, 25, 175, 100, 125, 100 ); 26 // instantiate an equilateral triangle: 27 triangle3 = new Triangle( 71, 125, 129, 125, 100, 175 ); 28 29 } 30 31 public void paint( Graphics g ) { 32 33 // draw the first triangle: 34 triangle1.draw( g ); 35 36 // fill the second triangle: 37 triangle2.fill( g ); 38 39 // fill the third triangle: 40 g.setColor( Color.red ); 41 triangle3.fill( g ); 42 43 } 44 45 } 46 47 // A triangle is a polygon with three sides: 48 class Triangle extends Polygon { 49 50 // Triangle constructor #1: 51 public Triangle() { 52 // invoke the constructor of the superclass Polygon: 53 super(); 54 } 55 56 // Triangle constructor #2: 57 public Triangle( int x1, int y1, 58 int x2, int y2, 59 int x3, int y3 ) { 60 61 // invoke the constructor of the superclass Polygon: 62 super(); 63 64 // the 'this' reference is optional: 65 this.addPoint( x1, y1 ); 66 this.addPoint( x2, y2 ); 67 this.addPoint( x3, y3 ); 68 69 } 70 71 // Instance methods: 72 public void draw( Graphics g ) { 73 g.drawPolygon( this ); 74 } 75 public void fill( Graphics g ) { 76 g.fillPolygon( this ); 77 } 78 79 }