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
there is no command directly to draw Triangle. For Drawing of triangle we have to use the concept of lines here.
i.e, g.drawLines(Coordinates of points)
You can use Processing library: https://processing.org/reference/PGraphics.html
There is a method called triangle():
g.triangle(x1,y1,x2,y2,x3,y3)
There is no direct method to draw a triangle.
You can use drawPolygon() method for this.
It takes three parameters in the following form:
drawPolygon(int x[],int y[], int number_of_points);
To draw a triangle:
(Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.)
Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100)
Do the following inside public void paint(Graphics g)
:
int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);
Similarly you can draw any shape using as many points as you want.
You should try using the Shape
s 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
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:
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:
Use a line algorithm to connect point A with point C, and in an outer loop, let point A wander towards point B with the same line algorithm and with the wandering coordinates, repeat drawing that line. You can probably also include a z delta with which is also incremented iteratively. For the line algorithm, just calculate two or three slopes for the delta change of each coordinate and set one slope to 1 after changing the two others proportionally so they are below 1. This is very important for drawing closed geometrical areas between connected mesh particles. Take a look at the Qt Elastic Nodes example and now imagine drawing triangles between the nodes after stretching this over a skeleton. As long as it will remain online