为什么当我想要获取控制器时,以下代码始终在控制台中显示null
?
RenewCardFXML2_controller controller=loader.getController();
,当我按下按钮时,控制台会打印null
。
我有两个控制器,想要使用主应用程序(会员卡)中的文本字段 - txt_numberOfCard_GENERAL
在第二个fxml文件中,它有自己的控制器。
txt_numberOfCard_GENERAL.getText
命令并使用其值。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package membershipcards;
import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.SplitPane;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import membershipcards.RenewCardFXML2_controller;
/**
*
* @author Primary
*/
public class mainGUIController implements Initializable {
@FXML
private ImageView logoimg;
@FXML
private SplitPane splitMenuContent;
@FXML
private Button btnCards;
@FXML
private Button btnRenewCard;
@FXML
private Button bntNewClient;
@FXML
private Button btnEditCard;
@FXML
private Button btnStatistics;
@FXML
private AnchorPane detailsPane;
@FXML
private Button btnCardN;
@FXML
public TextField txt_numberOfCard_GENERAL;
@FXML
public TextField txt_memberName_GENERAL;
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void loadCardsFXML1(ActionEvent event) {
try {
detailsPane = (AnchorPane) FXMLLoader.load(getClass().getResource("CardsFXML1.fxml"));
} catch (IOException ex) {
Logger.getLogger(mainGUIController.class.getName()).log(Level.SEVERE, null, ex);
}
splitMenuContent.getItems().set(1, detailsPane);
}
@FXML
private void loadRenewCardFXML2(ActionEvent event)throws IOException {
FXMLLoader loader = new FXMLLoader();
detailsPane = (AnchorPane) loader.load(getClass().getResource("RenewCardFXML2.fxml"));
splitMenuContent.getItems().set(1, detailsPane);
RenewCardFXML2_controller controller=loader.getController();
controller.setMGC(this);
System.out.println(controller);
}
}
答案 0 :(得分:0)
您调用的FXMLLoader.load(URL)
方法是static
方法。因此,您尚未在您创建的load
实例上调用FXMLLoader
,并且由于该实例尚未加载FXML,因此尚未初始化其controller
领域。
(一个好的IDE会在你的loader.load(...)
行上给你一个关于从非静态上下文或类似东西调用静态方法的警告。例如,Eclipse说“静态方法{{1}应该以静态方式访问。“)
以下内容可行:
load(URL)
请注意,您可以将该代码块的前两行减少为一行
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("RenewCardFXML2.fxml"));
detailsPane = loader.load();
splitMenuContent.getItems().set(1, detailsPane);
RenewCardFXML2_controller controller=loader.getController();