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



A cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface. In JavaFX a box is represented by the javafx.scene.shape.Cylinder class. This class contains 2 properties they are −

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

  • radius − This property represents the radius of the cylinder, you can set the value to this property using the setRadius() method.

To create a 3D Box you need to −

  • Instantiate this class.

  • Set the required properties using the setter methods or, bypassing 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.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);    } }

Output

Updated on: 2020-05-16T06:39:53+05:30

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements