如何使用 id 获取 JavaFx 中的元素?

2024-03-28

我是 FXML 新手,我正在尝试使用以下命令为所有按钮单击创建一个处理程序switch。然而,为了做到这一点,我需要使用 和 id 获取元素。我已经尝试了以下方法,但由于某种原因(也许是因为我是在控制器类中而不是在主类中执行此操作),我收到了堆栈溢出异常。

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 作为引用来获取元素(例如按钮)?

该按钮的 fxml 块是:

<Button fx:id="exitBtn" contentDisplay="CENTER" mnemonicParsing="false"
        onAction="#handleButtonClick" text="Exit" HBox.hgrow="NEVER" HBox.margin="$x1"/>

使用控制器类,这样您就不需要使用查找。这FXMLLoader将为您将字段注入到控制器中。注射保证在initialize()方法(如果有的话)被调用

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 的根元素中指定控制器类:

<!-- 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(也许但不一定是您的控制器类)Application类)与

Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);   
// etc...     
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 id 获取 JavaFx 中的元素? 的相关文章

随机推荐