如何在 JavaFX 中建立 Box(3D)?
盒子是一種具有長度(深度)、寬度和高度的三維形狀。在 JavaFX 中,盒子用 javafx.scene.shape.Box 類表示。此類包含 3 個屬性,它們為 -
深度 - 此屬性表示盒子的深度,你可以使用 setDepth() 方法為此屬性設定值。
高度 - 此屬性表示盒子的高度,你可以使用 setHeight() 方法為此屬性設定值。
寬度 - 此屬性表示盒子的寬度,你可以使用 setWidth() 方法為此屬性設定值。
要建立一個 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.Box; import javafx.scene.shape.CullFace; import javafx.scene.shape.DrawMode; public class DrawingBox extends Application { public void start(Stage stage) { //Drawing a Box Box cube = new Box(); //Setting the properties of the Box(cube) cube.setDepth(150.0); cube.setHeight(150.0); cube.setWidth(150.0); //Setting other properties cube.setCullFace(CullFace.BACK); cube.setDrawMode(DrawMode.FILL); PhongMaterial material = new PhongMaterial(); material.setDiffuseColor(Color.BROWN); cube.setMaterial(material); //Translating the box cube.setTranslateX(300.0); cube.setTranslateY(150.0); cube.setTranslateZ(150.0); //Setting the perspective camera PerspectiveCamera cam = new PerspectiveCamera(); cam.setTranslateX(-150); cam.setTranslateY(25); cam.setTranslateZ(150); //Setting the Scene Group root = new Group(cube); Scene scene = new Scene(root, 595, 300, Color.BEIGE); scene.setCamera(cam); stage.setTitle("Drawing A Cube"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
輸出
廣告