FXMLLoader how to access components using FXID?

I am trying to figure out how to work with JavaFx. I built the application interface in Scene Builder. But I can’t access the component, since everyone is loading into the parent.

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

If I change Parent to Panel, I can access getChildren (), but it is not clear how to get control if I know fx: id ...

The question is even simpler. I added Label or TextField to Scene Builder. How do I change text from code if I know fx: id?

I'm desperate.

+5
source share
2 answers

You should create a controller class for your FXML document in which you can perform any functions you need to perform using the user interface components. You can annotate the fields in this class using @FXML and they will be populated by FXMLLoader by matching the fx:id attribute with the field name.

For more information, go through the tutorial and see Introduction to FXML Documentation .

A simple example:

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); } } 
+5
source

FXMLLoader.getNamespace () can be used, this is a map of named components.

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

Source: https://habr.com/ru/post/1206992/


All Articles