How to Draw Triangles in Java

By Luc Braybury

The Java programming interface contains an advanced graphics processing capability. Drawing simple shapes such as triangles is a matter of defining parameters for the shape within a frame. Setting these parameters is done through the use of certain data types and Java methods that instruct the program compiler on what to do when the methods are called. Overriding a special method called paintComponent ensures precise drawing of a defined shape.

Step 1

Import the Graphics, Point and Polygon awt packages and JFrame and JPanel swing packages. The code goes before the first class of your program and looks like this: import java.awt.Graphics;import java.awt.Point;import java.awt.Polygon;import javax.swing.JFrame;import javax.swing.JPanel;

Step 2

Create your triangle class and extend the JPanel class so that the triangle can be displayed to a screen. Your code should look like this, although you can name your program whatever you'd like:public class TriangleShape extends JPanel {}

Step 3

Override the paintComponent method in your main class. The instructions Java uses to draw the triangle are located in this method. The code looks like this, although you can name the data types whatever you'd like:public void paintComponent (Graphics g) { super.paintComponent (g); Dimension length = this.getSize(); Point p1 = new Point (size.width / 3, (2 * size.height) / 3); Point p2 = new Point(size.width / 2, size.height / 3); Point p3 = new Point((2 * size.width) / 3, (2 * size.height) / 3); int[] x = { p1.x, p2.x, p3.x }; int[] y = { p1.y, p2.y, p3.y }; Polygon triangle = new Polygon(x, y, x.length);The points p1, p2 and p3 define the vertexes of the the triangle. The int[] arrays and the triangle of type Polygon form the legs of the triangle. This code goes within the brackets of your main class.

Step 4

Create the main method, which instructs Java to create a frame upon which to draw the triangle and adds the triangle to the frame. The code is as follows, using your names for the data types:public static void main(String[] args) { TriangleShape t = new TriangleShape(); JFrame frame = new JFrame(); frame.getContentPane().add(t); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 100);;This code goes in the brackets of your main class, after the printComponent method.