如何使用 JavaFX 创建多边形?
多边形是使用存在于同一平面中的 n 条线形成的闭合图形。在 JavaFX 中,多边形由javafx.scene.shape.Polygon类表示。
要创建多边形,需要执行以下操作 -
实例化此类。
将线段的起始点和终点传递给类,以便绘制多边形,方法是将它们作为参数传递给构造函数,或使用 getPoints() 方法,如下所示 -
polygon.getPoints().addAll(new Double[]{ List of XY coordinates separated by commas });
将创建的节点(形状)添加到 Group 对象。
示例
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Polygon; public class DrawingPolygon extends Application { public void start(Stage stage) { //Drawing a polygon Polygon polygon1 = new Polygon(); //Setting the properties of the ellipse polygon1.getPoints().addAll(new Double[]{ 250.0, 50.0, 175.0, 150.0, 175.0, 250.0, 200.0, 250.0, 350.0, 150.0 }); //Setting other properties polygon1.setFill(Color.DARKCYAN); polygon1.setStrokeWidth(8.0); polygon1.setStroke(Color.DARKSLATEGREY); //Drawing a polygon Polygon polygon2 = new Polygon(); //Setting the properties of the ellipse polygon2.getPoints().addAll(new Double[]{ 410.0, 160.0, 430.0, 130.0, 470.0, 130.0, 490.0, 160.0, 470.0, 200.0, 430.0, 200.0 }); //Setting other properties polygon2.setFill(Color.CHOCOLATE); polygon2.setStrokeWidth(8.0); polygon2.setStroke(Color.BROWN); //Setting the Scene Group root = new Group(polygon1, polygon2); Scene scene = new Scene(root, 595, 300, Color.BEIGE); stage.setTitle("Drawing Polygon"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出
广告