多读书多实践,勤思考善领悟

JavaFX 3D Shape Box(盒子形状)

本文于1663天之前发表,文中内容可能已经过时。

长方体是三维或实心形状。长方体由6个矩形制成,它们以直角放置。使用方形面的长方体是一个立方体,如果面是矩形,而不是立方体,它看起来像一个鞋盒。

长方体是三维形状,具有长度(深度),宽度高度,如下图所示 -

长方体

在JavaFX中,三维框由名为Box的类表示。该类属于包javafx.scene.shape

通过实例化此类,您可以在JavaFX中创建Box节点。

这个类有3个double数据类型的属性,它们是 -

  • width - 框的宽度。
  • height - 盒子的高度。
  • depth - 盒子的深度。

要绘制三次曲线,您需要通过将值传递给此类的构造函数来将值传递给这些属性。这必须在实例化时以相同的顺序完成,如下所示 -

1
Box box = new Box(width, height, depth);

或者,通过使用他们各自的setter方法如下 -

1
2
3
setWidth(value);
setHeight(value);
setDepth(value);

绘制3D框的步骤

要在JavaFX中绘制3D框,请按照下面给出的步骤操作。

第1步:创建一个类

创建一个Java类并继承包javafx.applicationApplication类,并实现此类start()方法,如下所示 -

1
2
3
4
5
public class ClassName extends Application {  
@Override
public void start(Stage primaryStage) throws Exception {
}
}

第2步:创建一个盒子

您可以通过实例化名BOX的类来创建JavaFX中的Box,该类属于包javafx.scene.shape。您可以按如下方式实例化此类。

1
2
//Creating an object of the class Box 
Box box = new Box();

第3步:将属性设置为框

使用各自的setter方法设置3D框的属性,宽度,高度深度,如以下代码块所示。

1
2
3
4
//Setting the properties of the Box 
box.setWidth(200.0);
box.setHeight(400.0);
box.setDepth(200.0);

第4步:创建组对象

start()方法中,通过实例化名Group的类来创建组对象,该类属于包javafx.scene

将上一步中创建的Box(节点)对象作为参数传递给Group类的构造函数。这样做是为了将其添加到组中,如下所示 -

1
Group root = new Group(box);

第5步:创建场景对象

通过实例化名Scene的类来创建一个Scene,该类属于包javafx.scene。对于此类,传递在上一步中创建的Group对象(root)。

除了根对象之外,您还可以传递两个表示屏幕高度和宽度的双参数以及Group类的对象,如下所示 -

1
Scene scene = new Scene(group ,600, 300);

第6步:设置舞台的标题

您可以使用Stage类的setTitle()方法将标题设置为舞台。所述primaryStage是Stage对象,它被传递给场景类作为参数的启动方法。

使用primaryStage对象,将场景标题设置为Sample Application,如下所示。

1
primaryStage.setTitle("Sample Application");

第7步:将场景添加到舞台

您可以使用名为Stage的类的方法setScene()将Scene对象添加到舞台。使用以下方法添加在前面步骤中准备的Scene对象 -

1
primaryStage.setScene(scene);

第8步:显示舞台的内容

使用Stage类的名为show()的方法显示场景的内容,如下所示。

1
primaryStage.show();

第9步:启动应用程序

通过从main方法调用Application类的静态方法launch()来启动JavaFX应用程序,如下所示 -

1
2
3
public static void main(String args[]){   
launch(args);
}

以下是使用JavaFX生成3D框的程序。将此代码保存在名为BoxExample.java的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import javafx.application.Application; 
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Box;
import javafx.stage.Stage;

public class BoxExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Box
Box box = new Box();

//Setting the properties of the Box
box.setWidth(200.0);
box.setHeight(400.0);
box.setDepth(200.0);

//Creating a Group object
Group root = new Group(box);

//Creating a scene object
Scene scene = new Scene(root, 600, 300);

//Setting title to the Stage
stage.setTitle("Drawing a Box");

//Adding scene to the stage
stage.setScene(scene);

//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

使用以下命令从命令提示符编译并执行保存的java文件。

1
2
javac BoxExample.java 
java BoxExample

执行时,上面的程序生成一个显示3D Box的JavaFX窗口,如下所示 -

绘制3dBox