Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Draw a triangle

RicardoFurtadoRicardoFurtado Posts: 205Member
How can i draw a triangle in java. I need to draw a triangle, i've allready tried every book i have, and everything but i've only seen how to draw rectangles and other stuff. Please help me. This is for school.
My thanks in advance

Comments

  • arb123arb123 Posts: 696Member
    : How can i draw a triangle in java. I need to draw a triangle, i've allready tried every book i have, and everything but i've only seen how to draw rectangles and other stuff. Please help me. This is for school.
    : My thanks in advance
    :

    Draw a 3-sided polygon or 3 lines.
    [code]
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Polygon;

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class JTrianglePanel extends JPanel {

    /* (non-Javadoc)
    * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
    */
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Dimension size = 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[] xs = { p1.x, p2.x, p3.x };
    int[] ys = { p1.y, p2.y, p3.y };
    Polygon triangle = new Polygon(xs, ys, xs.length);

    g.fillPolygon(triangle);
    }

    public static void main(String[] args) {

    JTrianglePanel t = new JTrianglePanel();

    JFrame frame = new JFrame();
    frame.getContentPane().add(t);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100, 100);
    frame.show();
    }

    }
    [/code]

    ---------------------------------
    [size=1]HOWTO ask questions: http://catb.org/~esr/faqs/smart-questions.html[/size]

Sign In or Register to comment.