【问题标题】:FXMLLoader how to access the components by FXID?FXMLLoader 如何通过 FXID 访问组件?
【发布时间】:2014-11-16 22:27:39
【问题描述】:

我正在尝试弄清楚如何使用 JavaFx。 我在 Scene Builder 中构建了应用程序界面。但我无法访问该组件,因为所有加载到父。

Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

如果我更改“窗格”上的“父级”,我可以访问 getChildren(),但是如果我知道 fx:id,则不清楚如何获得控制权...

这个问题就更简单了。我在 Scene Builder 中添加了 Label 或 TextField。如果我知道 fx:id,如何从代码中更改它的文本?

我很绝望。

【问题讨论】:

    标签: java javafx scenebuilder


    【解决方案1】:

    您应该为您的 FXML 文档创建一个控制器类,您可以在其中执行您需要执行的涉及 UI 组件的任何功能。您可以使用@FXML 注释该类中的字段,它们将由FXMLLoader 填充,将fx:id 属性与字段名称匹配。

    通过tutorial 了解更多详细信息,并查看Introduction to FXML documentation

    简单示例:

    Sample.fxml:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <?import javafx.scene.layout.VBox?>
    <?import javafx.scene.control.Label?>
    <?import javafx.scene.control.Button?>
    
    <VBox xmlns:fx="http://javafx.com/fxml/1" fx:controller="SampleController">
        <Label fx:id="countLabel"/>
        <Button fx:id="incrementButton" text="Increment" onAction="#increment"/>
    </VBox>
    

    SampleController.java:

    import javafx.fxml.FXML;
    import javafx.scene.control.Label;
    
    
    public class SampleController {
    
        private int count = 0 ;
    
        @FXML
        private Label countLabel ;
    
        @FXML
        private void increment() {
            count++;
            countLabel.setText("Count: "+count);
        }
    }
    

    SampleMain.java:

    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Scene;
    import javafx.stage.Stage;
    
    public class SampleMain extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            Scene scene = new Scene(FXMLLoader.load(getClass().getResource("Sample.fxml")), 250, 75);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    【讨论】:

    • 我在哪里打电话给increment()?如果我在 SampleMain 中使用对控制器的引用调用它,程序就会崩溃
    【解决方案2】:

    FXMLLoader.getNamespace()可以用,这是命名组件的映射。

    FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
    Parent root = loader.load();
    TextField foo = (TextField)loader.getNamespace().get("exampleFxId");
    

    【讨论】:

    • 这很有趣:自从第一次预发布以来,我几乎每天都在使用 FX8,而我以前从未见过这种方法。我认为使用控制器类的标准方法更好,因为它提供了清晰的关注点分离并鼓励更好的整体设计,但我可以看到这在某些情况下可能会有一些用途。
    • 我同意我也只使用控制器,只是 API 中一个有用的钩子
    猜你喜欢
    • 2021-10-27
    • 2022-11-29
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多