为什么在这种情况下抛出NullPointerException?

时间:2016-03-21 13:47:02

标签: java javafx nullpointerexception

我知道使用未初始化的对象(例如NullPointerException)会导致Button button;,然后尝试在button= new Button()之前使用它。但是,在这种情况下,我无法理解为什么以及在哪里出错了。

我有Main课程:

public class Main extends Application {
private Stage primaryStage;
private BorderPane mainLayout;

@Override
public void start(Stage primaryStage) throws IOException {
    this.primaryStage=primaryStage;
    this.primaryStage.setTitle("Employee App");
    showMainView();
    showMainItems();
}

 public void showMainView() throws IOException{
     FXMLLoader loader= new FXMLLoader();
     loader.setLocation(Main.class.getResource("view/MainView.fxml"));
     this.mainLayout=loader.load();
     Scene scene= new Scene(this.mainLayout);
     this.primaryStage.setScene(scene);
     this.primaryStage.show();
 }

 public void showMainItems() throws IOException{
     FXMLLoader loader= new FXMLLoader();
     loader.setLocation(Main.class.getResource("view/MainItemsView.fxml"));
     BorderPane mainItems=loader.load();
     mainLayout.setCenter(mainItems);
 }
 public void showEletricalScene() throws IOException{
     FXMLLoader loader= new FXMLLoader();
     loader.setLocation(Main.class.getResource("electrical/ElectricalDeptView.fxml"));
     BorderPane eletricalDpet=loader.load();
     mainLayout.setCenter(eletricalDpet);
 }
public static void main(String[] args) {
    launch(args);
}
}

我的控制器,我试图调用Main类中的方法来显示/加载另一个视图。

public class MainItemsController {
private Main main;
@FXML private void gotEletrical() throws IOException{
    this.main.showEletricalScene();
    }

  }

在我试图致电showEletricalScene之前,一切都运转良好。我已经固定了我的控制器,一切都很好,除了下面这个令人讨厌的错误:

Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.Trampoline.invoke(Unknown Source)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
... 51 more
Caused by: java.lang.NullPointerException
   at   employee.view.MainItemsController.gotEletrical(MainItemsController.java:11)
... 60 more

任何帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

您已定义

private Main main;

然后尝试调用

this.main.showEletricalScene();

之前,您已将值main分配给null