After all I am near to Christmas, My hands are shaking so cold: P. Today I’m writing about the post of how to create a 3d cube box in JavaFX. Well I’ve you have already read my previous post of how to create Cube in JavaFX using the technique I’ve described.

 

We’ll create here one function which can create a cube box using parameter of width. Even if we create a 3D in JavaFX, The Object will not look like a real 3D because there is absence of good Camera stuffs class. But hope these things will arrive very soon.

Here is the JavaFX function which can create the Cube3D

public StackPane getObject(double width){
	StackPane pane = new StackPane();
	double r = (Math.random()*1);
	double g = (Math.random()*1);
	double b = (Math.random()*1);
	double depth = width;
	double height = width;

	for(int i = 0 ; i<6; i++){
		final Rectangle rt = new Rectangle();
		rt.setWidth(width);
		rt.setHeight(height); 
		rt.setStrokeWidth(1);  		

		Color color = Color.color(r, g, b);
		Light.Point light = new Light.Point();
		light.setX(100);
		light.setY(100);
		light.setZ(50);
		Lighting lighting = new Lighting();
		lighting.setLight(light);
		lighting.setSurfaceScale(5.0);		

		rt.setFill(color);
		rt.setEffect(lighting); 
		rt.setTranslateZ(depth); 		
		rt.setSmooth(true);  
		pane.getChildren().add(rt);
		switch(i){
			case 1: //DOWN
					rt.getTransforms().add(new Rotate(270,width/2,depth/2,0,Rotate.X_AXIS));
					rt.setTranslateZ(depth*0.5);    
					rt.setHeight(depth);
					rt.setTranslateY(height*0.5);
					break;
			case 2: //LEFT
					rt.setTranslateZ((depth*0.5));     
					rt.getTransforms().add(new Rotate(90,depth/2,height/2,0,Rotate.Y_AXIS));
					rt.setWidth(depth);
					rt.setTranslateX(-(width*0.5-1)); 
					break;
			case 3: //RIGHT     
					rt.setTranslateZ((depth*0.5));
					rt.getTransforms().add( new Rotate(90,depth/2,height/2,0,Rotate.Y_AXIS));                        
					rt.setWidth(depth);
					rt.setTranslateX((width*0.5)); 
					break;
			case 4: //UP
					rt.setTranslateZ((depth*0.5));     
					rt.setTranslateY(-(height*0.5));
					rt.getTransforms().add(new Rotate(270,width/2,depth/2,0,Rotate.X_AXIS));
					rt.setHeight(depth);
					break;
			case 5: 
					//BACK
					rt.setTranslateZ(0);                        
					break;

		}
	}

	return pane;
}

After making this function for cube you can invoke this function and you will get the instance of StackPane. This way we can actually create 3D Cube.

A simple demo of Cube is given below


Source Code: CubeDemo

Have a good day and Merry Christmas 2012 :)