如何使用id在JavaFx中获取元素? [英] how do I get an element in JavaFx using an id?

查看:1970
本文介绍了如何使用id在JavaFx中获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是FXML的新手,我正在尝试使用开关为所有按钮点击创建一个处理程序。但是,为了做到这一点,我需要使用和id获取元素。我尝试了以下但由于某种原因(可能是因为我在控制器类中而不是在主节点上)我得到了堆栈溢出异常。

I am new to FXML and I am trying to create a handler for all of the button clicks using a switch. However, in order to do so, I need to get the elements using and id. I have tried the following but for some reason (maybe because I am doing it in the controller class and not on the main) I get a stack overflow exception.

public class ViewController {
public Button exitBtn;

public ViewController() throws IOException {
    Parent root = FXMLLoader.load(getClass().getResource("mainWindow.fxml"));
    Scene scene = new Scene(root);

    exitBtn = (Button) scene.lookup("#exitBtn");
}

}

那么我如何使用它的id作为参考获得一个元素(例如一个按钮)?

So how will I get an element (for example a button) using it's id as a reference?

该按钮的fxml块是:

The fxml block for the button is:

< Button fx:id =exitBtncontentDisplay =CENTERmnemonicParsing =falseonAction =#handleButtonClicktext =ExitHBox.hgrow =从不HBox.margin =$ x1/>

推荐答案

使用控制器类,这样您就不需要使用查找了。 FXMLLoader 会将字段注入控制器。注入保证在 initialize()方法(如果有的话)被调用之前发生

Use a controller class, so that you don't need to use a lookup. The FXMLLoader will inject the fields into the controller for you. The injection is guaranteed to happen before the initialize() method (if you have one) is called

public class ViewController {

    @FXML
    private Button exitBtn ;

    @FXML
    private Button openBtn ;

    public void initialize() {
        // initialization here, if needed...
    }

    @FXML
    private void handleButtonClick(ActionEvent event) {
        // I really don't recommend using a single handler like this,
        // but it will work
        if (event.getSource() == exitBtn) {
            exitBtn.getScene().getWindow().hide();
        } else if (event.getSource() == openBtn) {
            // do open action...
        }
        // etc...
    }
}

在FXML的根元素中指定控制器类:

Specify the controller class in the root element of your FXML:

<!-- imports etc... -->
<SomePane xmlns="..." fx:controller="my.package.ViewController">
<!-- ... -->
    <Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1" />
    <Button fx:id="openBtn" contentDisplay="CENTER" mnemonicParsing="false" onAction="#handleButtonClick" text="Open" HBox.hgrow="NEVER" HBox.margin="$x1" />
</SomePane>

最后,从你的控制器类以外的类加载FXML(可能,但不一定,你的应用程序类)

Finally, load the FXML from a class other than your controller class (maybe, but not necessarily, your Application class) with

Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);   
// etc...     

这篇关于如何使用id在JavaFx中获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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