[英]JavaFX controller is null when instantiated
我已經堅持了幾個小時。 我不知道為什么我的 JavaFX 控制器指向 null。 我在scene builder
中制作了一個 JavaFX GUI,將控制器類添加到我的項目中,並使用其適當的骨架代碼。 但是當我在我的start
方法中實例化控制器時,它指向 null。
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class App extends Application{
public static void main(String[] args) {
launch(args);
}
public static SampleController controller;
@Override
public void start(Stage stage) throws Exception {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("testProjectFx.fxml"));
Parent root = loader.load();
controller = (SampleController) loader.getController();
System.out.println("controller is : " + controller);
Scene scene = new Scene(root, 300, 300);
stage.setTitle("FXML Welcome");
stage.setScene(scene);
stage.show();
} catch(Exception e){
e.printStackTrace();
}
}
}
import javafx.fxml.FXML;
import javafx.scene.control.Label;
public class SampleController {
@FXML
private Label firstLabel;
}
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Label fx:id="firstLabel" layoutX="314.0" layoutY="135.0" text="Label" />
</children>
</AnchorPane>
cd /home/hexaquarks/vscode/testProject ; /usr/bin/env /usr/lib/jvm/java-11-openjdk-amd64/bin/java --module-path /home/hexaquarks/Downloads/javafx-sdk-11.0.2/lib --add-modules javafx.controls,javafx.fxml,javafx.swing -Dfile.encoding=UTF-8 @/tmp/cp_s5yrrw0jqsav930qkowo7m19.argfile App
Aug. 11, 2021 1:30:27 P.M. javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 16 by JavaFX runtime of version 11.0.2
controller is : null
使用文件夾樹:
Testproject
├── .vscode
├── bin
├── lib
└── src
├── App.java
├── SampleController.java
└── testProjectFx.fxml
我按照此處和此處以及其他一些 StackOverflow 頁面中提到的說明進行操作。 我正在完全按照提到的方式復制說明,但我的控制器仍然為空。
我缺乏想法,有誰知道我做錯了什么?
我需要在.fxml
文檔的根標記中手動添加fx:controller="SampleController"
,在我的例子中是<AnchorPane>
標記,現在它可以工作了。
<AnchorPane (...) fx:controller="SampleController">
<children>
(...)
</children>
</AnchorPane>
如果使用“場景生成器”,則進入左下角的“控制器”選項卡並在文本字段“控制器類”中輸入start()
方法中給出的所選實例名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.