A program containing a method named drawTriangle, which is invoked twice

The output of the TriangleMethodDemo applet.

 

Here, we will examine the construction of a method which draws an isosceles (two sides equal) triangle on a flat base, in the form of a tent. We are designing the method, so we can choose the parameters that will be required. For example, we could require three pairs of coordinates, but for our isosceles flat-based triangles, we will choose:

Rather than dive straight into writing a method, we will approach it in stages, introducing the basic statements involved in drawing a triangle, then moving towards bundling them up into a method with parameters.

Here are some Java statements which draw a triangle with a bottom corner 80 pixels in and 200 pixels down, with a base of 100 and a height of 110. First, we draw from the left end of the base to the right. Only the horizontal position changes:

g.drawLine(80, 200, 80+100, 200);

Secondly, we draw from the right of the base to the apex, we divide the base by 2 to find the mid-point.

g.drawLine(80+100, 200, 80+100/2, 200-110);

Thirdly, we draw from the apex to the bottom left.

g.drawLine(80+100/2, 200-110, 80, 200);

Rather than calculating each point as a single number, we have left some of them as expressions to show the calculations involved. Later we will simplify these calculations.

Hosted by www.Geocities.ws

1