JavaFX Polygon Tutorial

0
JavaFX Polygon class creates a new instance of polygon.

It needs the coordinates of all points of Polygon.

Creating a Polygon :

Polygon polygon = new Polygon();
polygon.getPoints().addAll(new Double[]{5.0,5.0,40.0,20.0,20.0,40.0});

Here polygon take an array of x,y coordinates.
getPoints() get the coordinates of points.

Constructors :

  • Polygon()Creates an empty instance of Polygon.
  • Polygon(double… points)Creates a new instance of Polygon with given coordinates of x,y.

Example of polygon:


package javafxtuts;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

/**
 *
 * @author JavaFXtuts.com
 */
public class Javafxtuts extends Application {
    
    @Override
    public void start(Stage primaryStage) {
         Pane root = new Pane();
         
        //creating polygon using empty constructor 
        Polygon polygon = new Polygon();
        polygon.getPoints().addAll(50.0,100.0,150.0,50.0,250.0,100.0,250.0,250.0,50.0,250.0);
            
            
        // To set outlier color of Polygon to Black
        polygon.setStroke(Color.DARKGREEN);
        
        
        // To set interier color of Polygon to DARKCYAN
        polygon.setFill(Color.DARKCYAN);
        //To set the width of the stroke using setStrokeWidth()
        polygon.setStrokeWidth(3);
        root.getChildren().addAll(polygon);
        Scene scene = new Scene(root, 250, 220);
        
        primaryStage.setTitle("javafxtuts.com");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
    
}

Output :

Explain :

  • Polygon polygon = new Polygon();
    It creates an empty state of Polygon.
  • polygon.getPoints().addAll(50.0,100.0,150.0,50.0,250.0,100.0,250.0,250.0,50.0,250.0);
    It gets the coordinates of all the pointes of polygon using an array.
  • Here it have five points so it draws a pentagon using these points.
Share.

Leave A Reply