如何在 JavaFX 中创建圆柱体 (3D)?

javafxobject oriented programmingprogramming更新于 2025/4/14 17:52:17

圆柱体是一种封闭的固体,它有两个平行(大多为圆形)的底部,底部由曲面连接。在 JavaFX 中,盒子由 javafx.scene.shape.Cylinder 类表示。此类包含 2 个属性,它们是 −

  • height − 此属性表示圆柱体的高度,您可以使用 setHeight() 方法将值设置为此属性。

  • radius −此属性表示圆柱体的半径,您可以使用 setRadius() 方法将值设置为此属性。

要创建 3D 框,您需要 −

  • 实例化此类。

  • 使用 setter 方法设置所需属性,或将它们作为参数传递给构造函数。

  • 将创建的节点(形状)添加到 Group 对象。

示例

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;
import javafx.stage.Stage;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.Cylinder;
import javafx.scene.shape.DrawMode;
import javafx.scene.transform.Rotate;
public class DrawingCylinder extends Application {
   public void start(Stage stage) {
      //绘制圆柱体
      Cylinder cylinder = new Cylinder();
      //设置Box(cube)的属性
      cylinder.setHeight(250.0);
      cylinder.setRadius(100.0);
      //设置其他属性
      cylinder.setCullFace(CullFace.BACK);
      cylinder.setDrawMode(DrawMode.FILL);
      PhongMaterial material = new PhongMaterial();
      material.setDiffuseColor(Color.BROWN);
      cylinder.setMaterial(material);
      //平移
      cylinder.setTranslateX(300.0);
      cylinder.setTranslateY(250.0);
      cylinder.setTranslateZ(150.0);
      //设置透视相机
      PerspectiveCamera cam = new PerspectiveCamera();
      cam.setTranslateX(-50);
      cam.setTranslateY(25);
      cam.setTranslateZ(0);
      cam.setRotationAxis(Rotate.X_AXIS);
      cam.setRotate(-25);
      //设置场景
      Group root = new Group(cylinder);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      scene.setCamera(cam);
      stage.setTitle("Drawing A Cylinder");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

输出


相关文章