您应该为FXML文档创建一个控制器类,在其中可以执行需要执行的涉及UI组件的任何功能。您可以使用注释该类中的字段,
@FXML并使用填充属性
FXMLLoader,将
fx:id属性与字段名称匹配。
通读本教程以获取更多详细信息,并查看FXML文档简介。
简单的例子:
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); }}


