Draw a Triangle using a Line2D

To draw a triangle, we are using Line2D class of package java.awt.geom.*. This class provides a line segment in (x, y) coordinate space. We have draw three line segments using the class Line2D to create a triangle.

Draw a Triangle using a Line2D

     

This section illustrates you how to draw a triangle using a Line2D.

To draw a triangle, we are using Line2D class of package java.awt.geom.*. This class provides a line segment in (x, y) coordinate space. We have draw three line segments using the class Line2D to create a triangle. 

The setPaint() method paints the line segment.

 

 

Here is the code of DrawTriangleUsingLine.java

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.geom.Line2D;

public class DrawTriangleUsingLine2D extends JApplet {
  public void init() {
  setBackground(Color.lightGray);
  }
  public void paint(Graphics g) {
  Graphics2D g2d = (Graphics2D) g;
  g2d.setPaint(Color.red);
  g2d.draw(new Line2D.Double(50,150,150,150 ));
  g2d.draw(new Line2D.Double(50,50,150,150 ));
  g2d.draw(new Line2D.Double(50,50,50,150 ));
  }
  public static void main(String s[]) {
  JFrame frame = new JFrame("Show Triangle");
  JApplet applet = new DrawTriangleUsingLine2D();
  frame.getContentPane().add("Center", applet);
  applet.init();
  frame.setSize(300250);
  frame.show();
  }
}

Output will be displayed as:

Download Source Code

Advertisements

 

We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Draw a Triangle using a Line2D

Posted on: October 16, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: Draw a Triangle using a Line2D  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
vijay kumar
October 12, 2012
java code

1)draw the shape * ** *** **** 2) * ** *** **** 3) * *** ***** *******

Ads

 

Ads