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:
Video of the Day
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);
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) {
This code goes in the brackets of your main class, after the printComponent method.
Video of the Day