FXMLLoader如何通过FXID访问组件?

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

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

如果我在“Pane”上更改“Parent”,我可以访问getChildren(),但如果我知道fx:id,则不清楚如何获得控制权…

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

我绝望了。

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

阅读本教程以获取更多详细信息,并查看FXML文档简介 。

简单的例子:

Sample.fxml:

         

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); } } 

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

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