JavaFX

JavaFX 3D Shapes Example

Photo of Andreas PomarolliAndreas PomarolliApril 1st, 2016Last Updated: April 24th, 2019
0 1,627 17 minutes read

This is a JavaFX 3DShape example. Any shape, drawn in a three-dimensional space, having three dimensions (length, width, and depth) is known as a 3D shape.

JavaFX 8 offers two types of 3D shapes.

  • Predefined shapes
  • User-defined shapes

Box,Sphere, andCylinder are three predefined 3D shapes that you can use in your JavaFX applications. You can also create any type of 3D shapes using a triangle mesh. TheBox,Sphere, andCylinder classes represent the three predefined shapes. TheMeshView class represents a user-defined 3D shape in aScene.

 
The following table shows an overview of the whole article:

The following examples uses Java SE 8 and JavaFX 2.2.

1. Using Predefined 3D Shapes

1.1 The Code

Fx3DShapeExample1.java

import javafx.application.Application;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.shape.Box;import javafx.scene.shape.Cylinder;import javafx.scene.shape.Sphere;import javafx.stage.Stage;public class Fx3DShapeExample1 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create a BoxBox box = new Box(100, 100, 100);box.setTranslateX(150);box.setTranslateY(0);box.setTranslateZ(400);// Create a SphereSphere sphere = new Sphere(50);sphere.setTranslateX(300);sphere.setTranslateY(-5);sphere.setTranslateZ(400);// Create a CylinderCylinder cylinder = new Cylinder(40, 120);cylinder.setTranslateX(500);cylinder.setTranslateY(-25);cylinder.setTranslateZ(600);// Create a LightPointLight light = new PointLight();light.setTranslateX(350);light.setTranslateY(100);light.setTranslateZ(300);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add the Shapes and the Light to the GroupGroup root = new Group(box, sphere, cylinder, light);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 400, 200, true);// Add the Camera to the Scenescene.setCamera(camera);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example with Predefined 3D Shapes");// Display the Stagestage.show();}}

1.2 Introduction

JavaFX 8 provides the following three built-in 3D geometric shapes:

  • Box
  • Sphere
  • Cylinder

The shapes are represented by instances of theBox,Sphere, andCylinder classes. The classes inherit from theShape3D class, which contains three properties that are common to all types of 3D shapes:

  • Material
  • Draw mode
  • Cull face

The properties specific to a shape type are defined in the specific class defining theShape. All shapes are nodes. Therefore, you can apply transformations to them. You can position them at any point in the 3D space using thetranslateX,translateY, andtranslateZ transformations.

1.3 The Box

A Box is defined by the following three properties:

  • width
  • height
  • depth

The Box class contains two constructors:

  • Box()
  • Box(double width, double height, double depth)

The no-args constructor creates aBox with width, height, and depth of 2.0 each. The other constructor lets you specify the dimensions of theBox. The center of theBox is located at the origin of its local coordinate system.

The following snippet of code creates aBox with width 100, height 200 and depth 100. After the creation, theBox will be transformed.

// Create a BoxBox box = new Box(100, 100, 100);box.setTranslateX(150);box.setTranslateY(0);box.setTranslateZ(400);

1.4 The Sphere

ASphere is defined by only one property named radius. TheSphere class contains three constructors:

  • Sphere()
  • Sphere(double radius)
  • Sphere(double radius, int divisions)

The no-args constructor creates aSphere of radius 1.0. The second constructor lets you specify the radius of theSphere. The third constructor lets you specify the radius and divisions. A 3D sphere is made up of many divisions, which are constructed from connected triangles. The value of the number of divisions defines the resolution of theSphere. The higher the number of divisions, the smoother theSphere looks.

The following snippet of code creates aSphere with radius 50. After the creation, theSpere will be transformed.

// Create a SphereSphere sphere = new Sphere(50);sphere.setTranslateX(300);sphere.setTranslateY(-5);sphere.setTranslateZ(400);

1.5 The Cylinder

A Cylinder is defined by two properties:

  • radius
  • height

The radius of theCylinder is measured on the XZ plane. The axis of theCylinder is measured along the y-axis. The height of theCylinder is measured along its axis. TheCylinder class contains three constructors:

  • Cylinder()
  • Cylinder(double radius, double height)
  • Cylinder(double radius, double height, int divisions)

The no-args constructor creates aCylinder with a 1.0 radius and a 2.0 height. The second constructor lets you specify the radius and height properties. The third constructor lets you specify the number of divisions, which defines the resolution of theCylinder. The higher the number of divisions, the smoother theCylinder looks.

The following snippet of code creates aCylinder with radius 40 and height 120. After the creation, theCylinder will be transformed.

// Create a CylinderCylinder cylinder = new Cylinder(40, 120);cylinder.setTranslateX(500);cylinder.setTranslateY(-25);cylinder.setTranslateZ(600);

The details about the creation ofPointLight andPerspectiveCamera will be discussed in the following chapters.

1.6 The GUI

The program creates the three shapes and positions them in the space. It creates aLight, which is an instance of thePointLight, and positions it in the space. The light is used to light the 3D shapes. All shapes and the light are added to aGroup, which is added to theScene. To view the shapes, you need to add aCamera to theScene. The program adds aPerspectiveCamera to theScene.

Using Predefined 3D Shapes
Using Predefined 3D Shapes

2. Specifying the Shape Material

2.1 The Code

Fx3DShapeExample2.java

import javafx.application.Application;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.image.Image;import javafx.scene.paint.Color;import javafx.scene.paint.PhongMaterial;import javafx.scene.shape.Box;import javafx.stage.Stage;public class Fx3DShapeExample2 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create a BoxBox box = new Box(100, 100, 100);box.setTranslateX(250);box.setTranslateY(0);box.setTranslateZ(400);// Create the MaterialPhongMaterial material = new PhongMaterial();material.setDiffuseColor(Color.TAN);// Set the material for the boxbox.setMaterial(material);// Create a Box with textureBox textbox = new Box(100, 100, 100);textbox.setTranslateX(450);textbox.setTranslateY(50);textbox.setTranslateZ(400);// Create the MaterialPhongMaterial textureMaterial = new PhongMaterial();// Create the ImageImage image = new Image("file:/img/core-logo-java.jpg");textureMaterial.setDiffuseColor(Color.BEIGE);textureMaterial.setDiffuseMap(image);// Set the material for the boxtextbox.setMaterial(textureMaterial);// Create a Light PointLight light = new PointLight();light.setTranslateX(250);light.setTranslateY(100);light.setTranslateZ(300);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(200);camera.setTranslateY(-50);camera.setTranslateZ(300);// Create the Group with both BoxesGroup root = new Group(box, textbox);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 400, 200, true);// Add the Camera to the Scenescene.setCamera(camera);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example with specified Material");// Display the Stagestage.show();}}

AMaterial is used for rendering the surface of shapes. You can specify theMaterial for the surface of 3D objects using theMaterial property, which is defined in theShape3D class. TheMaterial property is an instance of the abstract classMaterial. JavaFX provides thePhongMaterial class as the only concrete implementation ofMaterial. The following properties are defined in thePhongMaterial class:

  • diffuseColor
  • diffuseMap
  • specularColor
  • specularMap
  • selfIlluminationMap
  • specularPower
  • bumpMap

ThePhongMaterial class contains three constructors:

  • PhongMaterial()
  • PhongMaterial(Color diffuseColor)
  • PhongMaterial(Color diffuseColor, Image diffuseMap, Image specularMap, Image bumpMap, Image selfIlluminationMap)

The no-args constructor creates aPhongMaterial with the diffuse color asColor.WHITE. The other two constructors are used to create aPhongMaterial with the specified properties.

The following snippet of code creates aBox, creates aPhongMaterial with tan diffuse color, and sets theMaterial to theBox:

// Create a BoxBox box = new Box(100, 100, 100);box.setTranslateX(250);box.setTranslateY(0);box.setTranslateZ(400);// Create the MaterialPhongMaterial material = new PhongMaterial();material.setDiffuseColor(Color.TAN);// Set the material for the boxbox.setMaterial(material);

In the second case, we use anImage as the diffuse map to have texture for theMaterial, as shown in the following code:

// Create a Box with textureBox textbox = new Box(100, 100, 100);textbox.setTranslateX(450);textbox.setTranslateY(50);textbox.setTranslateZ(400);// Create the MaterialPhongMaterial textureMaterial = new PhongMaterial();// Create the ImageImage image = new Image("file:/img/core-logo-java.jpg");textureMaterial.setDiffuseColor(Color.BEIGE);textureMaterial.setDiffuseMap(image);// Set the material for the boxtextbox.setMaterial(textureMaterial);

2.2 The GUI

The following example shows two boxes. OneBox with diffuse color and the otherBox with diffuse map. TheImage used for the diffuse map provides the texture for the surface of the secondBox.

Using specified Material for 3D Shapes
Using specified Material for 3D Shapes

3. Specifying the Draw Mode of Shapes

3.1 The Code

Fx3DShapeExample3.java

import javafx.application.Application;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.shape.Box;import javafx.scene.shape.Cylinder;import javafx.scene.shape.DrawMode;import javafx.scene.shape.Sphere;import javafx.stage.Stage;public class Fx3DShapeExample3 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create a BoxBox box = new Box(100, 100, 100);box.setDrawMode(DrawMode.LINE);box.setTranslateX(150);box.setTranslateY(0);box.setTranslateZ(400);// Create a SphereSphere sphere = new Sphere(50, 20);sphere.setDrawMode(DrawMode.LINE);sphere.setTranslateX(300);sphere.setTranslateY(-5);sphere.setTranslateZ(400);// Create a CylinderCylinder cylinder = new Cylinder(40, 120, 5);cylinder.setDrawMode(DrawMode.LINE);cylinder.setTranslateX(500);cylinder.setTranslateY(-25);cylinder.setTranslateZ(600);// Create a LightPointLight light = new PointLight();light.setTranslateX(350);light.setTranslateY(100);light.setTranslateZ(300);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add the Shapes and the Light to the GroupGroup root = new Group(box, sphere, cylinder, light);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 400, 200, true);// Add the Camera to the Scenescene.setCamera(camera);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example with specified Draw Mode");// Display the Stagestage.show();}}

A 3DShape surface consists of many connected polygons made up of triangles. For example, aBox is made up of 12 triangles. Each side of theBox using two triangles. ThedrawMode property in theShape3D class specifies how the surface of 3D shapes is rendered. Its value is one of the constants of theDrawMode enum.

  • DrawMode.FILL
  • DrawMode.LINE

TheDrawMode.FILL is the default and it fills the interior of the triangles. TheDrawMode.LINE draws only the outline of the triangles. That is, it draws only lines connecting the vertices of the consecutive triangles.

The following code snippet creates aBox, aSphere and aCylinder withDrawMode.LINE:

// Create a BoxBox box = new Box(100, 100, 100);box.setDrawMode(DrawMode.LINE);box.setTranslateX(150);box.setTranslateY(0);box.setTranslateZ(400);// Create a SphereSphere sphere = new Sphere(50, 20);sphere.setDrawMode(DrawMode.LINE);sphere.setTranslateX(300);sphere.setTranslateY(-5);sphere.setTranslateZ(400);// Create a CylinderCylinder cylinder = new Cylinder(40, 120, 5);cylinder.setDrawMode(DrawMode.LINE);cylinder.setTranslateX(500);cylinder.setTranslateY(-25);cylinder.setTranslateZ(600);

3.2 The GUI

The following GUI shows the shapes. The program output is similar to the one shown in the above example. The program sets thedrawMode property of all shapes toDrawMode.LINE.

Using specified Draw Mode for 3D Shapes
Using specified Draw Mode for 3D Shapes

4. Using Cameras and Light Sources

4.1 The Code

Fx3DShapeExample4.java

import javafx.animation.Animation;import javafx.animation.RotateTransition;import javafx.application.Application;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.paint.Color;import javafx.scene.shape.Box;import javafx.scene.shape.CullFace;import javafx.scene.transform.Rotate;import javafx.stage.Stage;import javafx.util.Duration;public class Fx3DShapeExample4 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create a BoxBox box = new Box(100, 100, 100);box.setCullFace(CullFace.NONE);box.setTranslateX(250);box.setTranslateY(100);box.setTranslateZ(400);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add a Rotation Animation to the CameraRotateTransition rotation = new RotateTransition(Duration.seconds(2), camera);rotation.setCycleCount(Animation.INDEFINITE);rotation.setFromAngle(0);rotation.setToAngle(90);rotation.setAutoReverse(true);rotation.setAxis(Rotate.X_AXIS);rotation.play();// Create a red LightPointLight redLight = new PointLight();redLight.setColor(Color.RED);redLight.setTranslateX(250);redLight.setTranslateY(-100);redLight.setTranslateZ(250);// Create a green LightPointLight greenLight = new PointLight();greenLight.setColor(Color.GREEN);greenLight.setTranslateX(250);greenLight.setTranslateY(300);greenLight.setTranslateZ(300);// Add the Box and the Lights to the GroupGroup root = new Group(box, redLight, greenLight);// Enable Rotation for the Grouproot.setRotationAxis(Rotate.X_AXIS);root.setRotate(30);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 300, 400, true);// Add the Camera to the Scenescene.setCamera(camera);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example with a Camera");// Display the Stagestage.show();}}

4.2 Using Cameras

Cameras are used to render theScene. Two types of cameras are available.

  • Perspective camera
  • Parallel camera

The names of the cameras suggest the projection type they use to render theScene. ACamera in JavaFX is anode. They can be added to the scene graph and positioned like other nodes.

APerspectiveCamera defines the viewing volume for a perspective projection, which is a truncated right pyramid. TheCamera projects the objects contained within the near and far clipping planes onto the projection plane. Therefore, any objects outside the clipping planes are not visible.

The content that the camera will project onto the projection plane is defined by two properties in theCamera class.

  • nearClip
  • farClip

ThenearClip is the distance between theCamera and the near clipping plane. Objects closer to theCamera than thenearClip are not rendered.

ThefarClip is the distance between theCamera and the far clipping plane. Objects farther from theCamera than thefarClip are not rendered.

ThePerspectiveCamera class contains two constructors.

  • PerspectiveCamera()
  • PerspectiveCamera(boolean fixedEyeAtCameraZero)

The no-args constructor creates aPerspectiveCamera with thefixedEyeAtCameraZero flag set tofalse, which makes it behave more or less like a parallel camera where the objects in the scene at Z=0 stay the same size when the scene is resized.

The second constructor lets you specify this flag. If you want to view 3D objects with real 3D effects, you need to set this flag to true. Setting this flag totrue will adjust the size of the projected images of the 3D objects as theScene is resized. Making the scene smaller will make the objects look smaller as well.

The following code snippet creates aPerspectiveCamera and adds it to theScene:

// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add the Camera to the Scenescene.setCamera(camera);

You can move and rotate theCamera as you move and rotate nodes. To move it to a different position, use thetranslateX,translateY, andtranslateZ properties. To rotate, use theRotate transformation.

In the following code snippet, theGroup will be created and rotated along the X-Axis:

// Add the Box and the Lights to the GroupGroup root = new Group(box, redLight, greenLight);// Enable Rotation for the Grouproot.setRotationAxis(Rotate.X_AXIS);root.setRotate(30);

4.3 Using Light Sources

Similar to the real world, you need a light source to view the 3D objects in aScene. An instance of the abstract base classLightBase represents a light source. Its two concrete subclasses,AmbientLight andPointLight, represent an ambient light and a point light. TheLightBase class inherits from theNode class. Therefore, a light source is aNode and it can be added to the scene graph as any other nodes.

Want to master JavaFX ?
Subscribe to our newsletter and download theJavaFXProgramming Cookbookright now!
In order to get you prepared for your JavaFX development needs, we have compiled numerous recipes to help you kick-start your projects. Besides reading them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

A light source has three properties: light color, on/off switch, and a list of affected nodes.

The LightBase class contains the following two properties:

  • color
  • lightOn

Thecolor specifies thecolor of theLight. ThelightOn specifies whether theLight is on. ThegetScope() method of theLightBase class returns anObservableList, which is the hierarchical list of nodes affected by this light source. If the list is empty, the scope of the light source is universe, which means that it affects all nodes in theScene.

An instance of thePointLight class represents a point light source. A point light source is a fixed point in space and radiates lights equally in all directions. The intensity of a point light decreases as the distance of the of the lighted point increases from the light source.

In the following code snippet, a green and a red light will be created and added to theGroup:

// Create a red LightPointLight redLight = new PointLight();redLight.setColor(Color.RED);redLight.setTranslateX(250);redLight.setTranslateY(-100);redLight.setTranslateZ(250);// Create a green LightPointLight greenLight = new PointLight();greenLight.setColor(Color.GREEN);greenLight.setTranslateX(250);greenLight.setTranslateY(300);greenLight.setTranslateZ(300);// Add the Box and the Lights to the GroupGroup root = new Group(box, redLight, greenLight);

4.4 The GUI

The following example uses aPerspectiveCamera to view aBox. You have used two lights: one to light the front and the top faces and one to light the bottom face of theBox. TheCamera is animated by rotating it indefinitely along the x-axis. As theCamera rotates, it brings different parts of theBox into the view.

Using a Camera for 3D Shapes
Using a Camera for 3D Shapes

5. Creating Subscenes

5.1 The Code

Fx3DShapeExample5.java

import javafx.animation.Animation;import javafx.animation.RotateTransition;import javafx.application.Application;import javafx.geometry.Point3D;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.SceneAntialiasing;import javafx.scene.SubScene;import javafx.scene.layout.HBox;import javafx.scene.paint.Color;import javafx.scene.shape.Box;import javafx.scene.shape.CullFace;import javafx.scene.transform.Rotate;import javafx.stage.Stage;import javafx.util.Duration;public class Fx3DShapeExample5 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create the Sub-ScenesSubScene subscene1 = createSubScene(Rotate.Y_AXIS);SubScene subscene2 = createSubScene(Rotate.X_AXIS);// Create the HBox with both Sub-ScenesHBox root = new HBox(20, subscene1, subscene2);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 500, 300, true);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example with SubScenes");// Display the Stagestage.show();}private SubScene createSubScene(Point3D rotationAxis) {// Create a BoxBox box = new Box(100, 100, 100);box.setCullFace(CullFace.NONE);box.setTranslateX(250);box.setTranslateY(100);box.setTranslateZ(400);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add a Rotation Animation to the CameraRotateTransition rotation = new RotateTransition(Duration.seconds(2), camera);rotation.setCycleCount(Animation.INDEFINITE);rotation.setFromAngle(-10);rotation.setToAngle(10);rotation.setAutoReverse(true);rotation.setAxis(rotationAxis);rotation.play();// Create a red LightPointLight light = new PointLight(Color.RED);light.setTranslateX(250);light.setTranslateY(-100);light.setTranslateZ(290);// Add the Box and the Light to the GroupGroup root = new Group(box, light);// Enable Rotation for the Grouproot.setRotationAxis(Rotate.X_AXIS);root.setRotate(30);// Create the Sub-SceneSubScene subscene = new SubScene(root, 200, 200, true, SceneAntialiasing.BALANCED);// Add the Camera to the Sub-Scenesubscene.setCamera(camera);return subscene;}}

AScene can use only oneCamera. Sometimes, you may want to view different parts of aScene using multiple cameras. JavaFX 8 introduces this concept as subscenes. ASubScene is a container for a scene graph. It can have its own width, height, fill color, depth buffer, antialiasing flag, and camera. An instance of theSubScene class represents aSubScene. TheSubScene inherits from theNode class. Therefore, aSubScene can be used wherever aNode can be used. ASubScene can be used to separate 2D and 3D nodes in an application. You can use aCamera for theSubScene to view 3D objects that will not affect the 2D nodes in the other part of the main scene.

The following method creates aGroup which contains aBox, aCamera and aPointhLight. After creation, theGroup will be added to theSubScene. An animation is set up to rotate theCamera along the specified axis. Thestart() method creates two subscenes and adds them to anHBox. OneSubScene swings theCamera along the y-axis and another along the x-axis. TheHBox is added to the mainScene.

private SubScene createSubScene(Point3D rotationAxis) {// Create a BoxBox box = new Box(100, 100, 100);box.setCullFace(CullFace.NONE);box.setTranslateX(250);box.setTranslateY(100);box.setTranslateZ(400);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add a Rotation Animation to the CameraRotateTransition rotation = new RotateTransition(Duration.seconds(2), camera);rotation.setCycleCount(Animation.INDEFINITE);rotation.setFromAngle(-10);rotation.setToAngle(10);rotation.setAutoReverse(true);rotation.setAxis(rotationAxis);rotation.play();// Create a red LightPointLight light = new PointLight(Color.RED);light.setTranslateX(250);light.setTranslateY(-100);light.setTranslateZ(290);// Add the Box and the Light to the GroupGroup root = new Group(box, light);// Enable Rotation for the Grouproot.setRotationAxis(Rotate.X_AXIS);root.setRotate(30);// Create the Sub-SceneSubScene subscene = new SubScene(root, 200, 200, true, SceneAntialiasing.BALANCED);// Add the Camera to the Sub-Scenesubscene.setCamera(camera);return subscene;}

5.2 The GUI

The following image shows the effect of the above code:

Using SubScenes for 3D Shapes
Using SubScenes for 3D Shapes

6. Creating User-Defined Shapes

6.1 The Code

Fx3DShapeExample6.java

import javafx.animation.Animation;import javafx.animation.RotateTransition;import javafx.application.Application;import javafx.scene.Group;import javafx.scene.PerspectiveCamera;import javafx.scene.PointLight;import javafx.scene.Scene;import javafx.scene.paint.Color;import javafx.scene.shape.MeshView;import javafx.scene.shape.TriangleMesh;import javafx.scene.transform.Rotate;import javafx.stage.Stage;import javafx.util.Duration;public class Fx3DShapeExample6 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage) {// Create a MeshViewMeshView meshView = this.createMeshView();meshView.setTranslateX(250);meshView.setTranslateY(100);meshView.setTranslateZ(400);// Scale the Meshview to make it look biggermeshView.setScaleX(10.0);meshView.setScaleY(10.0);meshView.setScaleZ(10.0);// Create a Camera to view the 3D ShapesPerspectiveCamera camera = new PerspectiveCamera(false);camera.setTranslateX(100);camera.setTranslateY(-50);camera.setTranslateZ(300);// Add a Rotation Animation to the CameraRotateTransition rt = new RotateTransition(Duration.seconds(2), camera);rt.setCycleCount(Animation.INDEFINITE);rt.setFromAngle(-30);rt.setToAngle(30);rt.setAutoReverse(true);rt.setAxis(Rotate.Y_AXIS);rt.play();// Create the red Front LightPointLight redLight = new PointLight();redLight.setColor(Color.RED);redLight.setTranslateX(250);redLight.setTranslateY(150);redLight.setTranslateZ(300);// Create the green Back LightPointLight greenLight = new PointLight();greenLight.setColor(Color.GREEN);greenLight.setTranslateX(200);greenLight.setTranslateY(150);greenLight.setTranslateZ(450);// Add the Shapes and the Light to the GroupGroup root = new Group(meshView, redLight, greenLight);// Rotate the triangle with its lights to 90 degreesroot.setRotationAxis(Rotate.Y_AXIS);root.setRotate(90);// Create a Scene with depth buffer enabledScene scene = new Scene(root, 400, 300, true);// Add the Camera to the Scenescene.setCamera(camera);// Add the Scene to the Stagestage.setScene(scene);// Set the Title of the Stagestage.setTitle("An Example using a TriangleMesh");// Display the Stagestage.show();}public MeshView createMeshView() {float[] points = {50, 0, 0,45, 10, 0,55, 10, 0};float[] texCoords = { 0.5f, 0.5f,0.0f, 1.0f,1.0f, 1.0f};int[] faces = {0, 0, 2, 2, 1, 1,0, 0, 1, 1, 2, 2};// Create a TriangleMeshTriangleMesh mesh = new TriangleMesh();mesh.getPoints().addAll(points);mesh.getTexCoords().addAll(texCoords);mesh.getFaces().addAll(faces);// Create a NeshViewMeshView meshView = new MeshView();meshView.setMesh(mesh);return meshView;}}

6.2 Introduction

JavaFX lets you define a 3DShape using a mesh of polygons. An instance of the abstractMesh class represents the mesh data. TheTriangleMesh class is concrete subclass of theMesh class. ATriangleMesh represents a 3D surface consisting of a mesh of triangles.

An instance of theMeshView class represents a 3D surface. The data for constructing aMeshView is specified as an instance of theMesh.

ATriangleMesh needs to supply data for three aspects of a 3D object.

  • Points
  • Texture coordinates
  • Faces

Points are the vertices of the triangles in the mesh. You need to specify the (x, y, z) coordinates of vertices in an array. Suppose v0, v1, v2, v3, v4, and so on are the points in 3D space that represent the vertices of the triangles in a mesh. Points in aTriangleMesh are specified as anArray of floats.

The texture of a 3D surface is provided as an image that is a 2D object. Texture coordinates are points in a 2D plane, which are mapped to the vertices of triangles. You need to think of the triangles in a mesh unwrapped and placed onto a 2D plane. Overlay the image that supplies the surface texture for the 3D shape onto the same 2D plane. Map the vertices of the triangles to the 2D coordinates of the image to get a pair of (u, v) coordinates for each vertex in theMesh. Thearray of such (u, v) coordinates is the texture coordinate. Suppose t0, t1, t2, t3, t4, and so on are the texture coordinates.

Faces are the planes created by joining the three edges of the triangles. Each triangle has two faces: a front face and a back face. A face is specified in terms of indices in the points and texture coordinates arrays. A face is specified as v0, t0, v1, t1, v2, t2, and so on, where v1 is the index of the vertex in the points array and t1 is the index of the vertex in the texture coordinatesArray.

6.3 Creating a 3D Triangle

You may argue that a triangle is a 2DShape, not a 3D shape. It is agreed that a triangle is a 2D shape. You will create a triangle in a 3D space using aTriangleMesh. The triangle will have two faces. This example is chosen because it is the simplest shape you can create with a mesh of triangles. In case of a triangle, theMesh consists of only one triangle.

The triangle can be created using aMesh of one triangle. Let us create the points array for theTriangleMesh object.

float[] points = {50, 0, 0,  // v0 (iv0 = 0)45, 10, 0, // v1 (iv1 = 1)55, 10, 0  // v2 (iv2 = 2)};

The second part of the figure maps the vertices of the triangle to a unit square. You can create the texture coordinates array as follows:

float[] texCoords = { 0.5f, 0.5f, // t0 (it0 = 0)0.0f, 1.0f, // t1 (it1 = 1)1.0f, 1.0f  // t2 (it2 = 2)};

Using the points and texture coordinates arrays, you can specify the faces array as follows:

int[] faces = {0, 0, 2, 2, 1, 1, // iv0, it0, iv2, it2, iv1, it1 (front face)0, 0, 1, 1, 2, 2  // iv0, it0, iv1, it1, iv2, it2 back face};

Once you have the points, texture coordinates, and faces arrays, you can construct aTriangleMesh object as follows:

// Create a TriangleMeshTriangleMesh mesh = new TriangleMesh();mesh.getPoints().addAll(points);mesh.getTexCoords().addAll(texCoords);mesh.getFaces().addAll(faces);

ATriangleMesh provides the data for constructing a user-defined 3D object. AMeshView object creates the surface for the object with a specifiedTriangleMesh.

// Create a NeshViewMeshView meshView = new MeshView();meshView.setMesh(mesh);

6.4 The GUI

The following image shows a triangle using aTriangleMesh. It adds two different lights to light the two faces of the triangle. AnAnimation rotates theCamera, so you can view both sides of the triangle in different colors.

Using a TriangleMesh for 3D Shapes
Using a TriangleMesh for 3D Shapes

7. Download Java Source Code

This was an example ofjavafx.scene.shape.Shape3D

Download
You can download the full source code of this example here:JavaFx3DShapeExample.zip
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Tags
Photo of Andreas PomarolliAndreas PomarolliApril 1st, 2016Last Updated: April 24th, 2019
0 1,627 17 minutes read
Photo of Andreas Pomarolli

Andreas Pomarolli

Andreas has graduated from Computer Science and Bioinformatics at the University of Linz. During his studies he has been involved with a large number of research projects ranging from software engineering to data engineering and at least web engineering. His scientific focus includes the areas of software engineering, data engineering, web engineering and project management. He currently works as a software engineer in the IT sector where he is mainly involved with projects based on Java, Databases and Web Technologies.

Related Articles

The JavaFX Print API

July 8th, 2016

JavaFX WebView Example

October 13th, 2016

JavaFX Canvas Example

May 18th, 2016

JavaFX CSS Tutorial

May 5th, 2016

The JavaFX Media API

August 8th, 2016

JavaFX 2D Shape Example

October 21st, 2016
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.