当我尝试更改JavaFX中的场景时出现NullPointException

时间:2019-03-22 12:39:55

标签: java javafx

我将开始说这个问题已经被问过两次了,但是其中一个没有答案,另一个似乎与我的问题不符。

基本上,我有一个复杂的FXML文件,其中有一个空窗格,应根据用户单击的内容来填充不同的场景。

问题是,我不断收到错误,而且我不明白为什么,因为我在另一个程序中使用了相同的方法,但没有问题,因此执行相同的操作。

public class Controller {

@FXML
  public AnchorPane toolPane;

  public void cubePane() {
try {
      FXMLLoader loader = new FXMLLoader(getClass().getResource("pyramidPane.fxml"));
      AnchorPane pane = loader.load();
      toolPane.getChildren().setAll(pane);

    } catch (IOException e){
      System.out.println(e);
    }

  }

Stacktrace:

    Caused by: java.lang.reflect.InvocationTargetException 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:498) 
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71) 
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:498) 
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275) 
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771) 
... 45 more 
Caused by: java.lang.IllegalStateException: Location is not set. 
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434) 
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409) 
at sample.Controller.cubePane(Controller.java:19) 
... 55 more

1 个答案:

答案 0 :(得分:-1)

当您输入 cubePane 时, toolPane 的值为 null ,因为它没有实例化。因此,不能在空对象上调用任何方法。