How to create a Box (3D) in JavaFX?


A box is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a box is represented by the javafx.scene.shape.Box class. This class contains 3 properties they are −

  • depth − This property represents depth of the box, you can set value to this property using the setDepth() method.

  • height − This property represents the height of the box, you can set value to this property using the setHeight() method.

  • width − This property represents the width of the box, you can set value to this property using the setWidth() method.

To create a 3D Box you need to −

  • Instantiate this class.

  • Set the required properties using the setter methods or, by passing them as arguments to the constructor.

  • Add the created node (shape) to the Group object.

Example

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);
   }
}

Output

Updated on: 16-May-2020

422 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements