首页 > 文章列表 > 如何在JavaFX中绘制几何2D形状?

如何在JavaFX中绘制几何2D形状?

javafx 绘制 几何形状
119 2023-08-27

一般来说,2D形状是可以在XY平面上绘制的几何图形,包括线条、矩形、圆等。

javafx.scene.shape包提供了各种类,每个类代表/定义了一个2D几何对象或对它们的操作。名为Shape的类是JavaFX中所有2D形状的基类。

创建2D形状

要使用JavaFX绘制2D几何形状,您需要:

  • 实例化类 - 实例化相应的类。例如,如果要绘制一个圆,您需要实例化Circle类,如下所示:

//Drawing a Circle
Circle circle = new Circle();
  • 设置属性 - 使用其相应类的方法设置形状的属性。例如,要绘制一个圆,您需要中心和半径,您可以分别使用setCenterX()、setCenterY()和setRadius()方法来设置它们。

//Setting the properties of the circle
circle.setCenterX(300.0f);
circle.setCenterY(135.0f);
circle.setRadius(100.0f);
  • 将形状对象添加到组中 − 最后,将创建的形状作为参数传递给组的构造函数,如下所示:

Group root = new Group(circle);

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
public class CircleExample extends Application {
   public void start(Stage stage) {
      //Drawing a Circle
      Circle circle = new Circle();
      //Setting the properties of the circle
      circle.setCenterX(300.0f);
      circle.setCenterY(135.0f);
      circle.setRadius(100.0f);
      //Creating a Group object
      Group root = new Group(circle);
      //Creating a scene object
      Scene scene = new Scene(root, 600, 300);
      //Setting title to the Stage
      stage.setTitle("Drawing a Circle");
      //Adding scene to the stage
      stage.setScene(scene);
      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出

如何在JavaFX中绘制几何2D形状?