This question already has an answer here:
- Triangle Draw Method 7 answers
Hey I know that it is simple to draw oval/rectangle and fill it using
g.fillOval(30, 40, 20, 20);
but how to draw a triangle? It would be the best if it would have random coordinates.
Using the legacy
Graphics
class, this would be done by using the legacy methoddrawPolygon(int[] x, int[] y, int pointCount)
.The newer class
Graphics2D
supports a much nicer implementation usingPath2D
s. You will need either thedraw(Shape)
orfill(Shape)
method. Given the fact that almost everywhere in Java aGraphics
object is actually aGraphics2D
object, you can cast it so, that is the way to go, IMHO.There are at least two basics ways you can achieve this, based on your needs.
You could use
Polygon
or you could make use the 2D Graphics Shape APIWhich you might choose comes down to your requirements.
Polygon
requires you to know, in advance the position of the points within 3D space, where theShape
API gives you more freedom to define the shape without caring about the position in advance.This makes the
Shape
API more flexible, in that you can define the shape once and simply translate theGraphics
context as needed and repaint it.For example...
Red is a
Polygon
, green is aShape
, which is translated into position...