/* * File: TriangleTest2.java * * Drawing triangles (an exercise) * * Copyright: Northeast Parallel Architectures Center * */ import java.applet.Applet; import java.awt.Graphics; import java.awt.Polygon; import java.awt.Color; public class TriangleTest2 extends Applet { // create references to three triangles: private Triangle triangle1, triangle2, triangle3; public void init() { // instantiate an isosceles triangle: triangle1 = new Triangle( 50, 25, 75, 100, 25, 100 ); // instantiate a right triangle: triangle2 = new Triangle( 125, 25, 175, 100, 125, 100 ); // instantiate an equilateral triangle: triangle3 = new Triangle( 71, 125, 129, 125, 100, 175 ); } public void paint( Graphics g ) { // draw the first triangle: triangle1.draw( g ); // fill the second triangle: triangle2.fill( g ); // fill the third triangle: g.setColor( Color.red ); triangle3.fill( g ); } } // A triangle is a polygon with three sides: class Triangle extends Polygon { // Triangle constructor #1: public Triangle() { // invoke the constructor of the superclass Polygon: super(); } // Triangle constructor #2: public Triangle( int x1, int y1, int x2, int y2, int x3, int y3 ) { // invoke the constructor of the superclass Polygon: super(); // the 'this' reference is optional: this.addPoint( x1, y1 ); this.addPoint( x2, y2 ); this.addPoint( x3, y3 ); } // Instance methods: public void draw( Graphics g ) { g.drawPolygon( this ); } public void fill( Graphics g ) { g.fillPolygon( this ); } }