double sceneWidth = 400.0, sceneHeight = 300.0; ... Polygon triangle = new Polygon( 0, sceneHeight, sceneWidth, sceneHeight, sceneWidth/2, 0);
Here is another program that draws a triangle using the JavaFX class Polygon
.
This time, all vertices are calculated using the scene dimensions.
import javafx.application.*; import javafx.stage.*; import javafx.scene.Scene; import javafx.scene.shape.*; import javafx.scene.paint.*; import javafx.scene.layout.*; public class TriangleDemo extends Application { public void start( Stage primaryStage ) { double sceneWidth = 400.0, sceneHeight = 300.0; double sceneCenterX = sceneWidth/2; double sceneCenterY = sceneHeight/2; // height and width of the triangle double triHeight = sceneHeight*0.75; double triWidth = sceneWidth*0.5; // y coordinate of base of triangle double triBaseY = sceneCenterY+triHeight/2; // top vertex of the triangle double triTopX = sceneCenterX; double triTopY = triBaseY-triHeight; // left and right vertices of the triangle double triLeftX = sceneCenterX-triWidth/2; double triLeftY = triBaseY; double triRightX = sceneCenterX+triWidth/2; double triRightY = triBaseY; // array of vertices x,y, x,y, x,y // in clockwise order double[] vertices = { triRightX, triRightY, triTopX, triTopY, triLeftX, triLeftY }; Polygon triangle = new Polygon( vertices ); triangle.setFill( new Color( 0.8, 0.2, 0.1, 1.0) ); // Axes through center of scene Line lineH = new Line( 0, sceneCenterY, sceneWidth, sceneCenterY ) ; lineH.setStroke( new Color( 0.2, 0.2, 0.2, 0.5) ); Line lineV = new Line( sceneCenterX, 0, sceneCenterX, sceneHeight ) ; lineV.setStroke( new Color( 0.2, 0.2, 0.2, 0.5) ); Pane pane = new Pane( triangle, lineH, lineV ); Scene scene = new Scene( pane, sceneWidth, sceneHeight, Color.FLORALWHITE ); primaryStage.setTitle("Triangle Demo"); primaryStage.setScene( scene ); primaryStage.show(); } }
The constructor for Polygon
looks like this:
public Polygon(double... points) // vertices as two X Y values, in clockwise order.
It is often more convenient to calculate the vertices
and put them into an array of double
arranged as pairs X-Y in clockwise order.
Then the array can be used in the constructor.
// array of vertices x,y, x,y, x,y in clockwise order
double[] vertices = { triRightX, triRightY, triTopX, triTopY, triLeftX, triLeftY };
Polygon triangle = new Polygon( vertices );
What is a regular polygon?