文档



JavaFX:FXML入门
4 使用FXML创建自定义控件(8版) 4 使用FXML创建自定义控件(8版)

加载FXML源文件并定义舞台和场景

CustomControlExample.java文件包含设置主应用程序类的代码。它定义了舞台和场景,并加载了FXML源文件。更具体地说,该类使用CustomControl类加载FXML源文件。

  1. 打开CustomControlExample.java文件。

  2. 删除包含对FXMLLoader类调用的代码行,如示例4-4所示。

    示例4-4 删除对FXMLLoader类的调用

    Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
    
  3. 创建CustomControl类的实例,并指定自定义控件的文本,如示例4-5所示。

    示例4-5 实例化CustomControl类

    CustomControl customControl = new CustomControl();
    customControl.setText("你好!");
    
  4. 删除设置舞台和场景的代码行,并按照示例4-6所示定义舞台和场景。

    示例4-6 定义舞台和场景

    stage.setScene(new Scene(customControl));
    stage.setTitle("自定义控件");
    stage.setWidth(300);
    stage.setHeight(200);
    stage.show();
    
  5. 按下Ctrl(或Cmd)+ Shift + I来修正导入语句。

创建自定义控件后,您可以像使用任何其他控件一样,在代码或标记中使用该控件的实例,如示例4-7示例4-8所示。

示例4-7 在代码中使用CustomControl类的实例

HBox hbox = new HBox();
CustomControl customControl = new CustomControl();
customControl.setText("你好世界!");
hbox.getChildren().add(customControl);

示例4-8 在标记中使用CustomControl类的实例

<HBox>
    <CustomControl text="你好世界!"/>
</HBox>

下载CustomControlExample.zip文件以查看自定义控件应用程序的完整源代码。

关闭窗口

目录

JavaFX: FXML入门

展开 折叠