如何使用ID在JavaFx中获取元素?

问题描述 投票:9回答:1

我是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"/>
java javafx fxml
1个回答
10
投票

使用控制器类,因此您无需使用查找。 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>

最后,从具有您的控制器类(也许但不一定是您的Application类)的其他类中加载FXML,并带有

Parent root = FXMLLoader.load(getClass().getResource("path/to/fxml"));
Scene scene = new Scene(root);   
// etc...     
© www.soinside.com 2019 - 2024. All rights reserved.