FXMLLoader how to access the components by FXID?

筅森魡賤 提交于 2019-11-28 23:54:32

You should create a controller class for your FXML document, in which you can perform any functionality you need to perform involving the UI components. You can annotate fields in that class with @FXML and they will be populated by the FXMLLoader, matching the fx:id attribute to the field name.

Work through the tutorial for more details, and have a look at the Introduction to FXML documentation.

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

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!