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

标签 java javafx fxml

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

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 block 是:

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

最佳答案

使用 Controller 类,这样您就不需要使用查找。 FXMLLoader 将为您将字段注入(inject) Controller 。注入(inject)保证在 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 的根元素中指定 Controller 类:

<!-- 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>

最后,从您的 Controller 类(可能但不一定是您的 Application 类)以外的类加载 FXML

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

关于java - 如何使用 id 获取 JavaFx 中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35067893/

相关文章:

java - 如何支持在 ExtensionFunction Saxon HE 9.7 中返回 ArrayList

java - 设置JVM的系统时间

java - javafx 应用程序中未显示按钮

java - FXMLLoader 如何加载 FXML 的 Controller ?

即使存在事件处理程序,javafx Controller 也不对事件执行任何操作

javafx - FXML:一种将子宽度/高度绑定(bind)到父宽度/高度的优雅方法

Java 将字符串转换为 URL 兼容版本

java - 有没有办法减少这条线

java - 如何访问 javafx 元素的子元素?

Java FX Platform.runLater(() -> 相当于长时间运行的任务