Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triangle Draw Method

Tags:

I have trouble drawing a triangle with the draw(Graphics g) method in Java. I can draw a rectangle like so:

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);

Where p represents "the top left corner of the shapes". How would I draw the triangle in the same manner?

Could someone give me an example for a standard triangle?

like image 310
Jon Snow Avatar asked Aug 12 '12 04:08

Jon Snow


2 Answers

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

  • drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
  • drawPolygon(Polygon p)
  • drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

  • http://docs.oracle.com/javase/tutorial/2d/geometry/arbitrary.html
like image 56
davidbuzatto Avatar answered Sep 27 '22 22:09

davidbuzatto


You should try using the Shapes API.

Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas

You should also read up on GeneralPath & Drawing Arbitrary Shapes.

This method is much easy to apply AffineTransformations to

like image 38
MadProgrammer Avatar answered Sep 27 '22 23:09

MadProgrammer