在启动类或者子启动类用法相同

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.net.URL;
import javafx.fxml.JavaFXBuilderFactory;

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    URL location = getClass().getResource("sample.fxml");
    FXMLLoader fxmlLoader = new FXMLLoader();
        fxmlLoader.setLocation(location);
        fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory());
        Parent root = fxmlLoader.load();
        secondWindow.setTitle("secondWindow");
        secondWindow.setScene(new Scene(root));

        MyController controller = fxmlLoader.getController();   //获取Controller的实例对象
        //Controller中写的初始化方法
        controller.Init();

        secondWindow.show();
}

public static void main(String[] args) {
    launch(args);
}

}


MyController:

package sample;

import com.sun.javafx.fxml.LoadListener;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.fxml.JavaFXBuilderFactory;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;

public class MyController implements Initializable {

@FXML
private Text myText;

@Override
public void initialize(URL location, ResourceBundle resources) {

} 

public void Init(){
Date now=new Date();
DateFormat df=new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
String dateTimeString=df.format(now);
myText.setText(dateTimeString);
}
}

fxml:

<AnchorPane prefHeight="269.0" prefWidth="595.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.MyController">
<children>
<Text fx:id="myText" layoutX="192.0" layoutY="139.0" strokeType="OUTSIDE" strokeWidth="0.0" wrappingWidth="228.126953125" />
</children>
</AnchorPane>


视频教程:

Aimls大佬解说