Breaking News

How to create a 3D Cube using JavaFX




1 - Open NetBeans IDE
2 - File > New Project > JavaFX > JavaFX Application > Next
3 - Name Your Project and click Finish
4 - Write this Code:

import javafx.animation.RotateTransition;
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.scene.shape.Box;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author IDEA Developers
 */
public class Main extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        
        Box box = createCube(); // element
        Group root = new Group(); //layout
        root.getChildren().add(box);
        
        PerspectiveCamera camera = new PerspectiveCamera();
        
        Scene scene = new Scene(root, 850, 650); //show scene
        scene.setCamera(camera);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    Box createCube(){
        Box box = new Box();
        box.setWidth(300); //x size
        box.setHeight(300); // y size
        box.setDepth(300);// z size
        
        box.setTranslateX(300);
        box.setTranslateY(300);
        box.setTranslateZ(0);
        
        PhongMaterial mat = new PhongMaterial();
        mat.setSpecularColor(Color.BLACK);
        mat.setDiffuseColor(Color.RED);
        
        box.setMaterial(mat);
        
        Rotate xRotation = new Rotate(25, Rotate.X_AXIS);
        Rotate yRotation = new Rotate(25, Rotate.Y_AXIS);
        box.getTransforms().addAll(xRotation, yRotation);
        
       RotateTransition rt = new RotateTransition(Duration.millis(1000), box);
       rt.setAxis(Rotate.X_AXIS);
       rt.setByAngle(360);
       rt.setCycleCount(10);
       rt.play();
       return box;
    }
   
    public static void main(String[] args) {
        launch(args);
    }
    
}

5 - Run Project and Enjoy

Full Video:


No comments