JavaFX和FXML。何时对组件的引用加载到控制器类中? [英] JavaFX and FXML. When are the references to components loaded into the controller class?

查看:584
本文介绍了JavaFX和FXML。何时对组件的引用加载到控制器类中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的fxml文件,带有一个复选框:

I have a very simple fxml file, with a checkbox:

...
<AnchorPane id="AnchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="jfx01.T01">
...
<CheckBox fx:id="checkBox1" text="CheckBox" />
...

非常简单的控制器类如下:

the very simple controller class is the following:

public class T01 extends Application {

    @FXML protected CheckBox checkBox1;

    @Override
    public void start(Stage primaryStage) throws IOException {
         Parent root = FXMLLoader.load(getClass().getResource("t01.fxml"));   
         primaryStage.setScene(new Scene(root));
         primaryStage.show();

         //here, here is the problem!
         System.out.println("checkBox1==null? "+ (checkBox1==null?"yes":"no"));

    }
}



此基本应用的输出是:



The output of this basic app is:

checkBox1==null? yes

在start方法中,组件显然已创建,但尚未分配给@FXML字段控制器类。作为没有其他错误的测试,我添加了一个按钮和一个事件。
分配了checkBox1 IS!

Inside the "start" method the components are obviously created, but not yet assigned to @FXML fields of the controller class. As a test that there aren't other errors, i've added a button and an event. There the checkBox1 IS assigned!

    @FXML protected void handleButton1Action(ActionEvent event) {
        System.out.println("button pressed");
        checkBox1.setSelected(!checkBox1.isSelected());
    }



问题



如果我不能使用start方法因为init还没有完成,那么init完成后第一个可用的方法是什么,所以组件可用?

Question

If I can't use start method because init is not yet complete, what is the first method available where the init is complete and so the components are available?

推荐答案

Controller应实现 javafx.fxml.Initializable 并覆盖 initialize(URL arg0,ResourceBundle res)方法。 CheckBox checkBox1 将被初始化,并且可以通过FXMLLoader为您提供 initialize 方法。方便的方法是将Controller和Main(扩展应用程序)类分开,因此app开始/入口点和FXML文件控制器应该是2个不同的类。

The Controller should implement javafx.fxml.Initializable and override initialize(URL arg0, ResourceBundle res) method. The CheckBox checkBox1 will be initialized and be avaliable in that initialize method for you by the FXMLLoader. The convenience way is to separate the Controller and Main (that extends Application) classes, so app starting/entry point and the FXML file controller should be 2 different classes.

这篇关于JavaFX和FXML。何时对组件的引用加载到控制器类中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆