Polygon is a shape with 'n' sides. For example, an Octagon has 8 sides. ‘Polygon’ class is used to define a polygon.
How to define a polygon?
You can define a polygon by specifying sequence of x and y coordinates for each side. Since Polygon is a closed shape, last point automatically connected to first point.
Polygon class provides following constructors to define a polygon.
public Polygon()
public Polygon(double... points)
points: the coordinates of the polygon vertices
Example
Polygon polygon1 = new Polygon();
Polygon polygon2 = new Polygon(15.0, 350.0, 150.0, 350.0, 75.0, 150.0);
FXML to create a triangle
<Polygon fx:id="triangle" fill="lightgreen" stroke="black" strokeWidth="5"
points="15.0, 350.0, 150.0, 350.0, 75.0, 150.0"/>
FXML to create Trapezium
<Polygon fx:id="trapezium" fill="lightsalmon" stroke="black" strokeWidth="5"
points="100.0, 50.0, 150.0, 50.0, 150.0, 100.0, 100.0, 150.0"/>
Find the below working application.
polygonDemo.fxml
<?import javafx.scene.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<Group xmlns:fx="http://javafx.com/fxml" fx:controller="com.sample.app.controller.PolygonController">
<Polygon fx:id="triangle" fill="lightgreen" stroke="black" strokeWidth="5"
points="15.0, 350.0, 150.0, 350.0, 75.0, 150.0"/>
<Polygon fx:id="trapezium" fill="lightsalmon" stroke="black" strokeWidth="5"
points="100.0, 50.0, 150.0, 50.0, 150.0, 100.0, 100.0, 150.0"/>
</Group>
PolygonController.java
package com.sample.app.controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.shape.Polygon;
public class PolygonController implements Initializable {
@FXML
private Polygon triangle;
@FXML
private Polygon trapezium;
@Override
public void initialize(URL location, ResourceBundle resources) {
}
}
PolygonDemo.java
package com.sample.app;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PolygonDemo extends Application {
private static final String FXML_FILE = "/polygonDemo.fxml";
private static final String STAGE_TITLE = "Polygon Demo";
public static void main(String args[]) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = (Parent) FXMLLoader.load(this.getClass().getResource(FXML_FILE));
Scene scene = new Scene(root, 300, 500, Color.WHITE);
primaryStage.setTitle(STAGE_TITLE);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Output
Previous Next Home
No comments:
Post a Comment