Home Answers Viewqa Java-Beginners Java draw triangle draw method?

 
 


baburaoganpatraoapte
Java draw triangle draw method?
1 Answer(s)      9 months ago
Posted in : Java Beginners

hi

how would i construct the draw method for an triangle using the 'public void draw (graphics g ) method? im unsure how to use the g.fillPolygon and g.drawPolygon?

i have this for drawing a rectangle and this works for a rectangle:

public void draw(Graphics g) {
    g.setColor(colorFill);
    g.fillRect(p.x, p.y, width, height);
    g.setColor(colorBorder);
    g.drawRect(p.x, p.y, width, height);
    drawHandles(g);
}
View Answers

August 13, 2012 at 6:03 PM


Here is an example that draws a triangle using drawPolygon method.

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

public class DrawTriangle extends JPanel {
  public void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.setColor(Color.red);
 Polygon polygon1= new Polygon();
 for (int i = 0; i < 3; i++){
  polygon1.addPoint((int) (40 + 50 * Math.cos(i * 2 * Math.PI / 3)),
  (int) (150 + 50 * Math.sin(i * 2 * Math.PI / 3)));
 }
 g.drawPolygon(polygon1);
 }

  public static void main(String[] args) {
  JFrame frame = new JFrame();
   frame.setSize(350, 250);
  Container contentPane = frame.getContentPane();
  contentPane.add(new DrawTriangle());
  frame.show();
  }
}

If you want to use Line2D class to draw a triangle, then please go through the following link:

http://www.roseindia.net/java/example/java/swing/graphics2D/triangle-line2d.shtml









Related Pages:

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.