Using FXML to Create a User Interface 使用FXML创建用户界面

时间:2021-07-01 17:02:43

This tutorial shows the benefits of using JavaFX FXML, which is an XML-based language that provides the structure for building a user interface separate from the application logic of your code.(这个教程演示了使用JavaFX FXML的好处,FXML是基于xml的语言,它提供了分离应用程序逻辑的构建用户界面的结构) If you started this document from the beginning, then you have seen how to create a login application using just JavaFX. (如果你从头开始阅读这个文档,你将看到怎么使用JavaFX创建一个登录程序)Here, you use FXML to create the same login user interface, separating the application design from the application logic, thereby making the code easier to maintain. (在这里,你使用FXML去创建一个相同的登录程序用户界面,它和应用程序的逻辑分开,从而达到使代码容易管理的目的)The login user interface you build in this tutorial is shown in Figure 4-1.(你要创建的登录用户界面如图4-1所示)

Figure 4-1 Login User Interface

Using FXML to Create a User Interface 使用FXML创建用户界面

The title of the application is "Welcome." (应用的标题是“Welcome”)This application has a gray background with a linen-like texture.(背景是亚麻布式的灰色北京) From top to bottom, the controls in this application are a TextField with the label "User Name," a PasswordField with the label "Password," and a Button with the label "Sign in."(从头到尾,控件依次是标签名为“User Name”的文本输入框,标签名为“Password”的密码文本,标签名为“SIgn in”的按钮)


This tutorial uses NetBeans IDE. Ensure that the version of NetBeans IDE that you are using supports JavaFX 2.2. See the System Requirements for details.
Set Up the Project(这个教程使用的是NetBeans集成开发环境,确保你使用的NetBeans支持JavaFX2.2,查看详细的系统要求)

Your first task is to set up a JavaFX FXML project in NetBeans IDE:(一开始你的任务是在NetBeans中建立JavaFX FXML工程)


From the File menu, choose New Project.(从文件目录,选择新的工程)


In the JavaFX application category, choose JavaFX FXML Application. Click Next.(在JavaFX工程分类中选择JavaFX FXML工程,点击下一步)


Name the project FXMLExample and click Finish.(命名这个工程的名字为FXMLExample,点击完成)

NetBeans IDE opens an FXML project that includes the code for a basic Hello World application. The application includes three files:(NetBeans打开一个FXML工程,包括了基本的Hello World工程的代码,这个工程包括三个文件)


FXMLExample.java. This file takes care of the standard Java code required for an FXML application.(FXMLExample.java,这个文件包含了FXML工程需要的标准java代码)


Sample.fxml. This is the FXML source file in which you define the user interface.(Sample.fxml,这个文件源码就是你定义用户界面的地方)

  • SampleController.java. This is the controller file for handling the mouse and keyboard input.(SampleController.java,这是处理鼠标和键盘输入的控制文件)

  • Rename Sample.java to FXMLExampleController.java so that the name is more meaningful for this application.(把Sample.java文件改名为FXMLExampleController.java,这个名字对这个工程更加有意义)

    1. In the Projects window, right-click Sample.java and chooseRefactor thenRename.(在工程界面,右键点击Sample.java,选择重构,接下来选择重命名)

    2. Enter FXMLExampleController, and click Refactor.(输入FXMLExampleController,点击重构)

  • Rename Sample.fxml to fxml_example.fxml.(重命名Sample.fxml文件为fxml_example.fxml)

    1. Right-click Sample.fxml and choose Rename.(右键点击Sample.fxml,选择重命名)

    2. Enter fxml_example and click OK.(输入fxml_example,点击OK)

    Load the FXML Source File(加载FXML源文件)

    The first file you edit is the FXMLExample.java file. (首先你要编辑的文件是FXMLExample.java)This file includes the code for setting up the application main class and for defining the stage and scene.(这个文件包含了建立工程main类和定义了stage和scene) More specific to FXML, the file uses the FXMLLoader class, which is responsible for loading the FXML source file and returning the resulting object graph.(针对FXML,这个文件使用了FXMLLoader类,这个类负责加载FXML源文件返回产生的对象图)

    Make the changes shown in bold in Example 4-1.(按照图片Example 4-1中黑体字进行修改)

    Example 4-1 FXMLExample.java

        @Override
    public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("fxml_example.fxml"));

    stage.setTitle("FXML Welcome");
    stage.setScene(new Scene(root, 300, 275));
    stage.show();
    }


     

    A good practice is to set the height and width of the scene when you create it, in this case 300 by 275; otherwise the scene defaults to the minimum size needed to display its contents.(一个好的习惯是当你创建它的时候设置好scene的高度和宽度,这个例子中是300高和275宽;否则的话scene默认是展示内容需要的最小长度)

    Modify the Import Statements(修改导入语句)

    Next, edit the fxml_example.fxml file. This file specifies the user interface that is displayed when the application starts. The first task is to modify the import statements so your code looks likeExample 4-2.(下面,编辑fxml_example.fxml文件,这个文件是指定应用启动的时候显示的用户界面。首先的工作是像Example 4-2修改import语句) 

    <?xml version="1.0" encoding="UTF-8"?>

    <?import javafx.geometry.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.text.*?>





     

    As in Java, class names can be fully qualified (including the package name),(像在java中,类名必须完整指定,包括包名在内) or they can be imported using the import statement, as shown inExample 4-2. (或者像在Example 4-2显示的import语句导入)If you prefer, you can use specific import statements that refer to classes.(如果你喜欢,你也可以使用特定的指向某个类的import语句)

    Create a GridPane Layout(创建GridPane布局)

    The Hello World application generated by NetBeans uses an AnchorPane layout.(这个Hello World工程netbeans使用AnchorPane布局来生成的) For the login form, you will use aGridPane layout because it enables you to create a flexible grid of rows and columns in which to lay out controls.(对于登录的表单来说,你讲使用gridpane布局,因为它让你可以创建放置控件的灵活的行和列)

    Remove the AnchorPane layout and its children and replace it with theGridPane layout inExample 4-3.(在Example 4-3删除AnchorPane布局和它的孩子用GridPane来替换)

    In this application, the GridPane layout is the root element of the FXML document and as such has two attributes.(在这个应用中,gridpane布局是FXML的根元素,本省有两个属性) Thefx:controller attribute is required when you specify controller-based event handlers in your markup. (fx:controller属性当你在你的标记中指定控制器基础的事件处理器时是必须的)Thexmlns:fx attribute is always required and specifies thefx namespace.(xmlns:fx属性是必须的,它指定了命令空间)

    The remainder of the code controls the alignment and spacing of the grid pane.(剩余的代码控制对齐和grid pane的间距) The alignment property changes the default position of the grid from the top left of the scene to the center.(alignment属性把grid默认的位置上左边改到中间) Thegap properties manage the spacing between the rows and columns, while thepadding property manages the space around the edges of the grid pane.(gap属性控制行和列之间的空间,padding属性控制围绕这个grid pane的边缘的控件)

    As the window is resized, the nodes within the grid pane are resized according to their layout constraints.(当窗口调整大小时,grid pane中的节点根据布局的约束调整大小) In this example, the grid remains in the center when you grow or shrink the window. (在这个例子中,当你放大缩小窗口,grid都保留在中间)The padding properties ensure there is a padding around the grid when you make the window smaller.(padding属性在你缩小窗口的时候保证围绕这个grid都有填充)

    Add Text and Password Fields(添加Text和Password文本域)

    Looking back at Figure 4-1, you can see that the login form requires the title “Welcome” and text and password fields for gathering information from the user.(回头看图片4-1,你看到登录表单需要标题“Welcome”和文本、密码域从用户那里搜集信息) The code inExample 4-4 is part of the GridPane layout and must be placed above the</GridPane> statement.(在Example 4-4中的代码是gridpane布局的一部分,它们必须放在</GridPane>语句的上面)

    Example 4-4 Text, Label, TextField, and Password Field Controls

        <Text text="Welcome" 
    GridPane.columnIndex="0" GridPane.rowIndex="0"
    GridPane.columnSpan="2"/>

    <Label text="User Name:"
    GridPane.columnIndex="0" GridPane.rowIndex="1"/>

    <TextField
    GridPane.columnIndex="1" GridPane.rowIndex="1"/>

    <Label text="Password:"
    GridPane.columnIndex="0" GridPane.rowIndex="2"/>

    <PasswordField fx:id="passwordField"
    GridPane.columnIndex="1" GridPane.rowIndex="2"/>


     

     

    The first line creates a Text object and sets its text value to Welcome.(第一行创建了文本对象设置它的值为Welcome) The GridPane.columnIndex andGridPane.rowIndex attributes correspond to the placement of the Text control in the grid. (GridPane.columnIndex和GridPane.rowIndex属性符合文本控件在grid中位值)The numbering for rows and columns in the grid starts at zero, and the location of theText control is set to (0,0), meaning it is in the first row of the first column.(grid中的行和列都是0开始的,文本控件的位置被设置成(0,0),这是第一行和第一列的意思) TheGridPane.columnSpan attribute is set to 2, making the Welcome title span two columns in the grid. (GridPane.columnSpan属性被设置成2,是Welcome标题在这个grid中跨越两列)You will need this extra width later in the tutorial when you add a style sheet to increase the font size of the text to 32 points.(在这个教程中你等一下需要额外的宽度,你要添加样式表把文本的字体大小改成32points)

    The next lines create a Label object with text User Name at column 1, row 0 and aTextField object to the right of it at column 1, row 1.(下一行在列1,行1创建了标签对象,它的文本是User Name,右边在列1行1创建了文本域对象) AnotherLabel and PasswordField object are created and added to the grid in a similar fashion.(另一个标签和密码域也用同样的样式被创建和添加)

    When working with a grid layout, you can display the grid lines, which is useful for debugging purposes. In this case, set thegridLinesVisible property to true using the statement <gridLinesVisible>true</gridLinesVisible>. Then, when you run the application, you see the lines for the grid columns and rows as well as the gap properties, as shown inFigure 4-2.

    Figure 4-2 Login Form with Grid Lines