首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javafx FXMLLoader类

Javafx FXMLLoader类
EN

Stack Overflow用户
提问于 2018-02-25 06:52:59
回答 1查看 2K关注 0票数 1

在我学习Javafx的时候,我已经学习了阶段,场景和场景图(树数据结构)(分支节点,叶节点)等。所以我知道场景图的基础知识,它必须包含一个根节点及其子节点,并且scene类需要一个类型为root node的参数,所以我的问题是,当我写下这一行的时候:

代码语言:javascript
复制
FXMLLoader load = new FXMLLoader(getClass.getResource("sample.fxml"));

我知道我在这里创建了一个FXMLLoader的对象,那么这里到底发生了什么呢?我只想知道当我使用FXMLLoader加载.fxml代码时会发生什么……它会像基本的方法那样创建一个没有.fxml的类吗?或者此FXMLLoader返回到根节点及其子节点。总之,我想知道这个FXMLLoader是如何工作的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-25 07:15:23

代码语言:javascript
复制
FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));

与任何其他类似的Java代码一样,它创建FXMLLoader类的一个实例。您还可以将其location属性设置为您指定的URL (基本上表示与您所在的类相同的包中的sample.fxml资源)。这不会加载或读取FXML文件,直到调用

代码语言:javascript
复制
loader.load();

调用此方法时,它将读取并分析FXML文件,并创建与FXML中的元素相对应的对象层次结构。如果FXML指定了控制器,它会将任何具有fx:id属性的元素注入到控制器中与该属性同名的@FXML-annotated字段中。一旦完成,它将调用控制器的initialize()方法(如果有),最后返回与FXML文件的根元素对应的对象。此对象还设置为root属性,因此以下代码相同:

代码语言:javascript
复制
loader.load();
Parent root = loader.getRoot();

代码语言:javascript
复制
Parent root = loader.load();

例如,假设您的FXML是

代码语言:javascript
复制
<BorderPane fx:controller="example.Controller">
  <top>
    <Label fx:id="header"/>
  </top>
  <bottom>
    <HBox>
      <children>
        <Button text="OK" fx:id="okButton" />
        <Button text="Cancel" fx:id="cancelButton" />
      </children>
    </HBox>
  </bottom>
</BorderPane>

然后

代码语言:javascript
复制
Parent root = loader.load();

导致执行的代码与在加载器中执行以下代码具有完全相同的效果:

代码语言:javascript
复制
public class FXMLLoader {

    // not a real method, but functionally equivalent to the load()
    // method for the example FXML above:
    public BorderPane load() {

        example.Controller controller = new example.Controller();
        this.controller = controller ;

        BorderPane borderPane = new BorderPane();
        this.root = borderPane ;

        Label header = new Label();
        controller.header = header ;
        borderPane.setTop(header);

        HBox hbox = new HBox();
        Button okButton = new Button();
        okButton.setText("OK");
        controller.okButton = okButton ;
        hbox.getChildren().add(okButton);

        Button cancelButton = new Button();
        cancelButton.setText("Cancel");
        controller.cancelButton = cancelButton ;
        hbox.getChildren().add(cancelButton);

        borderPane.setBottom(hbox);

        controller.initialize();

        return borderPane ;

    }
}

当然,由于它是在运行时读取FXML文件,所有这些实际上都是由反射完成的,但代码的效果是相同的。在这一点上,上述任何实际代码都不存在。

Introduction to FXML document提供了FXML文档的完整规范;显然,这里的内容太多了,无法在本文中涵盖所有内容。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48968476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档