JavaFX FXMLLoader getController NullPointerException [英] JavaFX FXMLLoader getController NullPointerException

查看:225
本文介绍了JavaFX FXMLLoader getController NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学校有一个项目,我必须开发一个程序,在该程序中,您首先可以选择是要从SQL DB保存/读取到SQL DB,还是要从XML保存/读取到XML.

I have a project in school where I have to develop a program where you first can choose whether you want to save/read to/from a SQL DB or to save/read to/from XML.

我制作了一个GUI,您可以在这两种方法之间进行选择.

I've made a GUI where you can choose between both methods.

用户单击按钮之一后,GUI关闭,并且MainMenu GUI打开. 现在,我需要在MainMenuController中知道用户选择了什么. 我在网上找到了一个方法,可以在第一个控制器中使用FXMLLoader.getController()调用MainMenuController.

The GUI closes after the user clicks on one of the buttons and the MainMenu GUI opens. Now I need to know in the MainMenuController what the user choose. I found online a Method to call the MainMenuController inside the first controller, with FXMLLoader.getController().

try {                       
    Stage stage = new Stage();
    FXMLLoader Loader = new FXMLLoader();
    Parent root = Loader.load(getClass().getResource("MainMenu.fxml"));

    MainMenuController mc = Loader.getController();
    mc.setSave("sql");

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}
catch (Exception e) {
    e.printStackTrace();
}

MainMenuController

MainMenuController

public class MainMenuController {   
    private String save = null;

    public void setSave(String save) {
        this.save=save;
    }
    public String getSave() {
        return save;
    }
}

但是当我尝试访问MainMenuController中的方法时,我得到

But when i try to access a method in MainMenuController I get a NullPointerException for

mc.setSave("sql")

推荐答案

首先,要了解此问题,您应该采取一些技巧来检测问题所在.

First ,to understand this issue ,you should make some tricks to detect where is your problem.When you do :

 System.out.println(mc);

您将发现结果为null.因此无法使用null对象调用setSave("sql"),由于没有指定文件的位置,所以得到了空控制器,但是可以将一些行更改为解决您的问题:

You will find the result is null.So you can not call setSave("sql") with null object,you got a null controller because your did not specify the location of your file,but you can change some lines to resolve your problem :

 try {
            Stage stage = new Stage();
            FXMLLoader fxm = new FXMLLoader(getClass().getResource("MainMenu.fxml"));

            Parent parent = (Parent) fxm.load();
            Scene scene = new Scene(parent);
            stage.setScene(scene);
            stage.show();
            FirstController mc = fxm.getController();
            System.out.println(mc);
            mc.setSave("sql");
        } catch (Exception e) {
            e.printStackTrace();
        }

这篇关于JavaFX FXMLLoader getController NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆