如何在 JavaFX 中建立一個圓柱體(3D)?


圓柱體是一個閉合實體,它有兩個平行的(通常是圓形的)底面,中間由一個曲面連線。在 JavaFX 中,一個圓柱體由 javafx.scene.shape.Cylinder 類表示。此類包含 2 個屬性,它們是:

  • height - 此屬性表示圓柱體的高度,可以使用 setHeight() 方法設定此屬性的值。

  • radius - 此屬性表示圓柱體的半徑,可以使用 setRadius() 方法設定此屬性的值。

要建立一個 3D 圓柱體,你需要:

  • 例項化此類。

  • 使用設定器方法設定所需屬性,或將其繞過建構函式作為引數。

  • 將建立的節點(形狀)新增到 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) {
      //Drawing a Cylinder
      Cylinder cylinder = new Cylinder();
      //Setting the properties of the Box(cube)
      cylinder.setHeight(250.0);
      cylinder.setRadius(100.0);
      //Setting other properties
      cylinder.setCullFace(CullFace.BACK);
      cylinder.setDrawMode(DrawMode.FILL);
      PhongMaterial material = new PhongMaterial();
      material.setDiffuseColor(Color.BROWN);
      cylinder.setMaterial(material);
      //Translating
      cylinder.setTranslateX(300.0);
      cylinder.setTranslateY(250.0);
      cylinder.setTranslateZ(150.0);
      //Setting the perspective camera
      PerspectiveCamera cam = new PerspectiveCamera();
      cam.setTranslateX(-50);
      cam.setTranslateY(25);
      cam.setTranslateZ(0);
      cam.setRotationAxis(Rotate.X_AXIS);
      cam.setRotate(-25);
      //Setting the Scene
      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);
   }
}

輸出

更新於: 16-May-2020

254 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告