微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

一般来说,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形状?

以上就是如何在JavaFX中绘制几何2D形状?的详细内容,更多请关注编程之家其它相关文章

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐