Javafx 简明教程
JavaFX - Application
正如我们已经了解的那样,JavaFX 是一个开源免费软件平台,允许用户开发可在各种设备上一致运行的客户端应用程序。使用 JavaFX,可以创建图形用户界面应用程序(GUI)以及 Internet 或桌面应用程序。所有这些应用程序都将在 Java 中开发。
As we have already learned, JavaFX is an open source free software platform, that allows a user to develop client applications that work consistently across various devices. Using JavaFX, one can create Graphical User Interface applications (GUIs), and Internet or Desktop applications as well. All these applications will be developed in Java.
在本章中,我们将详细讨论 JavaFX 应用程序的结构,并通过示例学习如何创建 JavaFX 应用程序。
In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example.
JavaFX Application Structure
一般而言,JavaFX 应用程序将具有三个主要组件,即 Stage, Scene 和 Nodes ,如下所示。
In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram.
Stage
一个舞台(窗口)包含 JavaFX 应用程序的所有对象。它由包 javafx.stage 的 Stage 类表示。主舞台由平台自身创建。创建的舞台对象作为 Application 类的 start() 方法的参数传递(在下一节中说明)。
A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section).
舞台有两个确定其位置的参数,即 Width 和 Height 。它分为内容区和装饰(标题栏和边框)。
A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders).
有五种类型的舞台可用 −
There are five types of stages available −
-
Decorated
-
Undecorated
-
Transparent
-
Unified
-
Utility
您必须调用 show() 方法以显示舞台的内容。
You have to call the show() method to display the contents of a stage.
Scene
场景表示 JavaFX 应用程序的物理内容。它包含场景图的所有内容。包 javafx.scene 的类 Scene 表示场景对象。在某个实例中,场景对象仅添加到一个舞台。
A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage.
您可以通过实例化 Scene 类来创建场景。您可以选择场景的大小,方法是将其尺寸(高度和宽度)连同 root node 一起传递给其构造函数。
You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor.
Scene Graph and Nodes
scene graph 是一个树状数据结构(分层),表示场景的内容。相比之下, node 是场景图的可视/图形对象。
A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph.
节点可能包括 −
A node may include −
-
Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc.
-
UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc.
-
Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc.
-
Media elements such as Audio, Video and Image Objects.
包 javafx.scene 的 Node 类表示 JavaFX 中的一个节点,这个类是所有节点的超类。
The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes.
节点有三种类型 −
A node is of three types −
-
Root Node − The first Scene Graph is known as the Root node.
-
Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types − Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. WebView − This node manages the web engine and displays its contents.
-
Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes.
必须将根节点传递到场景图。如果将组传递为根,则所有节点都将剪切到场景,场景大小的任何更改都不会影响场景的布局。
It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene.
Creating a JavaFX Application
要创建 JavaFX 应用程序,你需要实例化应用程序类并实现其抽象方法 start() 。在此方法中,我们将为 JavaFX 应用程序编写代码。
To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application.
Application Class
包 javafx.application 中的 Application 类是 JavaFX 中应用程序的入口点。要创建 JavaFX 应用程序,你需要继承该类并实现其抽象方法 start() 。在此方法中,你需要编写用于 JavaFX 图形的全部代码
The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics
在 main 方法中,你必须使用 launch() 方法启动应用程序。此方法在内部调用 Application 类的 start() 方法,如下所示:
In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program.
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
/*
Code for JavaFX application.
(Stage, scene, scene graph)
*/
}
public static void main(String args[]){
launch(args);
}
}
要在 start() 方法中创建典型的 JavaFX 应用程序,你需要执行以下步骤:
Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below −
-
Prepare a scene graph with the required nodes.
-
Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it.
-
Prepare a stage and add the scene to the stage and display the contents of the stage.
Preparing the Scene Graph
根据你的应用程序,你需要使用必需的节点准备一个场景图。由于根节点是第一个节点,因此你需要创建一个根节点。作为根节点,你可以从 Group, Region or WebView 中选择。
As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView.
Group − 一个 Group 节点由名称为 Group 的类表示,该类属于包 javafx.scene ,你可以通过实例化此类来创建一个 Group 节点,如下所示:
Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below.
Group root = new Group();
getChildren() 方法 Group 类提供一个 ObservableList 类的对象,保存节点。我们可以检索该对象,并将节点添加到其中,如下所示。
The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below.
//Retrieving the observable list object
ObservableList list = root.getChildren();
//Setting the text object as a node
list.add(NodeObject);
我们还可以通过在实例化时将节点对象传递给 Group 类及其构造函数来向组添加节点对象,如下所示。
We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below.
Group root = new Group(NodeObject);
Region − 这是所有基于 JavaFX Node 的 UI 控件的基类,例如 −
Region − It is the Base class of all the JavaFX Node-based UI Controls, such as −
-
Chart − This class is the base class of all the charts and it belongs to the package javafx.scene.chart. This class has two sub classes, which are − PieChart and XYChart. These two in turn have subclasses such as AreaChart, BarChart, BubbleChart, etc. used to draw different types of XY-Plane Charts in JavaFX. You can use these classes to embed charts in your application.
-
Pane − A Pane is the base class of all the layout panes such as AnchorPane, BorderPane, DialogPane, etc. This class belong to a package that is called as − javafx.scene.layout. You can use these classes to insert predefined layouts in your application.
-
Control − It is the base class of the User Interface controls such as Accordion, ButtonBar, ChoiceBox, ComboBoxBase, HTMLEditor, etc. This class belongs to the package javafx.scene.control. You can use these classes to insert various UI elements in your application.
在组中,您可以实例化上述任何类,并将其用作根节点,如下面的程序所示。
In a Group, you can instantiate any of the above-mentioned classes and use them as root nodes, as shown in the following program.
//Creating a Stack Pane
StackPane pane = new StackPane();
//Adding text area to the pane
ObservableList list = pane.getChildren();
list.add(NodeObject);
WebView − 此节点管理 Web 引擎并显示其内容。
WebView − This node manages the web engine and displays its contents.
下面是表示 JavaFX 节点类层次结构的图表。
Following is a diagram representing the node class hierarchy of JavaFX.
Preparing the Scene
JavaFX 场景由 javafx.scene 包的 Scene 类表示。您可以通过实例化此类来创建场景,如下面的代码块所示。
A JavaFX scene is represented by the Scene class of the package javafx.scene. You can create a Scene by instantiating this class as shown in the following code block.
在实例化时,必须将根对象传递给场景类的构造函数。
While instantiating, it is mandatory to pass the root object to the constructor of the scene class.
Scene scene = new Scene(root);
您还可以传递两个表示场景高度和宽度的双类型参数,如下所示。
You can also pass two parameters of double type representing the height and width of the scene as shown below.
Scene scene = new Scene(root, 600, 300);
Preparing the Stage
这是任何 JavaFX 应用程序的容器,它为应用程序提供了一个窗口。它由 javafx.stage 包的 Stage 类表示。此类的对象作为 Application 类 start() 方法的参数传递。
This is the container of any JavaFX application and it provides a window for the application. It is represented by the Stage class of the package javafx.stage. An object of this class is passed as a parameter of the start() method of the Application class.
使用这个对象,您可以在舞台上执行各种操作。主要是,您可以执行以下操作 −
Using this object, you can perform various operations on the stage. Primarily you can perform the following −
-
Set the title for the stage using the method setTitle().
-
Attach the scene object to the stage using the setScene() method.
-
Display the contents of the scene using the show() method as shown below.
//Setting the title to Stage.
primaryStage.setTitle("Sample application");
//Setting the scene to Stage
primaryStage.setScene(scene);
//Displaying the stage
primaryStage.show();
Lifecycle of JavaFX Application
JavaFX 应用程序类有三个生命周期方法,分别是 −
The JavaFX Application class has three life cycle methods, which are −
-
start() − The entry point method where the JavaFX graphics code is to be written.
-
stop() − An empty method which can be overridden, here you can write the logic to stop the application.
-
init() − An empty method which can be overridden, but you cannot create stage or scene in this method.
除了这些以外,它提供名为 launch() 的静态方法以启动 JavaFX 应用程序。
In addition to these, it provides a static method named launch() to launch JavaFX application.
由于 launch() 方法是静态的,您需要从静态上下文中(通常是 main)调用它。每当启动 JavaFX 应用程序时,将会按照(相同顺序)执行以下操作。
Since the launch() method is static, you need to call it from a static context (main generally). Whenever a JavaFX application is launched, the following actions will be carried out (in the same order).
-
An instance of the application class is created.
-
Init() method is called.
-
The start() method is called.
-
The launcher waits for the application to finish and calls the stop() method.
Terminating the JavaFX Application
当应用程序的最后一个窗口关闭时,JavaFX 应用程序将被隐式终止。您可以通过将布尔值“False”传递给静态方法* setImplicitExit()*(应从静态上下文中调用)来关闭此行为。
When the last window of the application is closed, the JavaFX application is terminated implicitly. You can turn this behavior off by passing the Boolean value “False” to the static method * setImplicitExit()* (should be called from a static context).
您可以使用 * Platform.exit()* 或 * System.exit*(int) 方法显式终止 JavaFX 应用程序。
You can terminate a JavaFX application explicitly using the methods * Platform.exit()* or * System.exit*(int).
Example - Creating an Empty Window
此部分教您如何创建一个显示空窗口的 JavaFX 样例应用程序。以下为步骤 −
This section teaches you how to create a JavaFX sample application which displays an empty window. Following are the steps −
Step 1: Creating a Class
创建一个 Java 类,继承包 javafx.application 中的类 Application ,然后实现该类的 start() 方法,如下所示。
Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class as follows.
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
Step 2: Creating a Group Object
在 start() 方法中,通过实例化属于包 javafx.scene 的名为 Group 的类创建一个组对象,如下所示。
In the start() method creates a group object by instantiating the class named Group, which belongs to the package javafx.scene, as follows.
Group root = new Group();
Step 3: Creating a Scene Object
通过实例化属于包 javafx.scene 的名为 Scene 的类,创建一个 Scene。向此类传递在上一步中创建的 Group 对象 (root) 。
Create a Scene by instantiating the class named Scene which belongs to the package javafx.scene. To this class, pass the Group object (root), created in the previous step.
除了根对象以外,您还可以将表示高度和宽度的两个双精度参数与 Group 类的对象一起传递,如下所示。
In addition to the root object, you can also pass two double parameters representing height and width of the screen along with the object of the Group class as follows.
Scene scene = new Scene(root,600, 300);
Step 4: Setting the Title of the Stage
您可以使用 Stage 类的 setTitle() 方法设置舞台的标题。 primaryStage 是 Stage 对象,它作为参数传递给场景类的 start 方法。
You can set the title to the stage using the setTitle() method of the Stage class. The primaryStage is a Stage object which is passed to the start method of the scene class, as a parameter.
使用 primaryStage 对象,将场景的标题设置为 Sample Application ,如下所示。
Using the primaryStage object, set the title of the scene as Sample Application as shown below.
primaryStage.setTitle("Sample Application");
Step 5: Adding Scene to the Stage
您可以使用名为 Stage 的类的 setScene() 方法,将 Scene 对象添加到舞台。使用此方法添加在之前的步骤中准备的 Scene 对象,如下所示。
You can add a Scene object to the stage using the method setScene() of the class named Stage. Add the Scene object prepared in the previous steps using this method as shown below.
primaryStage.setScene(scene);
Step 6: Displaying the Contents of the Stage
使用 Stage 类的名为 show() 的方法显示场景的内容,如下所示。
Display the contents of the scene using the method named show() of the Stage class as follows.
primaryStage.show();
Step 7: Launching the Application
通过从 main 方法以如下方式调用 Application 类的静态方法 launch() 启动 JavaFX 应用程序。
Launch the JavaFX application by calling the static method launch() of the Application class from the main method as follows.
public static void main(String args[]){
launch(args);
}
以下程序生成一个空 JavaFX 窗口。将此代码保存在名为 JavafxSample.java 的文件中
The following program generates an empty JavaFX window. Save this code in a file with the name JavafxSample.java
Example
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxSample extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//creating a Group object
Group group = new Group();
//Creating a Scene by passing the group object, height and width
Scene scene = new Scene(group ,600, 300);
//setting color to the scene
scene.setFill(Color.BROWN);
//Setting the title to Stage.
primaryStage.setTitle("Sample Application");
//Adding the scene to Stage
primaryStage.setScene(scene);
//Displaying the contents of the stage
primaryStage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxSample.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxSample
执行后,上述程序会生成如下所示的 JavaFX 窗口。
On executing, the above program generates a JavaFX window as shown below.
Example - Drawing a Straight Line
在前面的示例中,我们已经看到了如何创建空界面。在这个示例中,让我们使用 JavaFX 库尝试绘制一条直线。
In the previous example, we have seen how to create an empty stage, now in this example let us try to draw a straight line using the JavaFX library.
绘制直线的代码也遵循了前面的示例中提到的步骤。然而,差别发生在 start() 方法中。在这个方法中,我们通过实例化名为 Group 的类来创建一个 group 对象,该类属于 javafx.scene 包。将使用赋值方法创建的 Line(节点)对象作为 Group 类构造函数的参数传递,以便将其添加到组中。
This code to draw a line also follows the same steps mentioned in the previous example. However, the difference occurs in the start() method, where we create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Line (node) object, that is created using setter methods, as a parameter to the constructor of the Group class, in order to add it to the group.
将此代码保存在名为 DrawingLine.java 的文件中。
Save this code in a file with the name DrawingLine.java.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
public class DrawingLine extends Application{
@Override
public void start(Stage stage) {
//Creating a line object
Line line = new Line();
//Setting the properties to a line
line.setStartX(100.0);
line.setStartY(150.0);
line.setEndX(500.0);
line.setEndY(150.0);
//Creating a Group
Group root = new Group(line);
//Creating a Scene
Scene scene = new Scene(root, 600, 300);
//Setting title to the scene
stage.setTitle("Sample application");
//Adding the scene to the stage
stage.setScene(scene);
//Displaying the contents of a scene
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
使用以下命令,从命令提示符编译并执行已保存的 java 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls DrawingLine.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls DrawingLine
Example - Displaying Text
我们还可以在 JavaFX 场景中嵌入文本。此示例显示如何用 JavaFX 嵌入文本。将此代码保存在名为 DisplayingText.java 的文件中。
We can also embed text in JavaFX scene. This example shows how to embed text in JavaFX. Save this code in a file with name DisplayingText.java.
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
public class DisplayingText extends Application {
@Override
public void start(Stage stage) {
//Creating a Text object
Text text = new Text();
//Setting font to the text
text.setFont(new Font(45));
//setting the position of the text
text.setX(50);
text.setY(150);
//Setting the text to be added.
text.setText("Welcome to Tutorialspoint");
//Creating a Group object
Group root = new Group();
//Retrieving the observable list object
ObservableList list = root.getChildren();
//Setting the text object as a node to the group object
list.add(text);
//Creating a scene object
Scene scene = new Scene(root, 600, 300);
//Setting title to the Stage
stage.setTitle("Sample Application");
//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 文件。
Compile and execute the saved java file from the command prompt using the following commands.
javac --module-path %PATH_TO_FX% --add-modules javafx.controls DisplayingText.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls DisplayingText