尝试使用javafx将项目分配给选择框时发生InvocationTargetException

时间:2014-08-05 10:34:45

标签: java javafx

将选项添加到我的选择框的简单尝试会产生InvocationTargetException。我真的不明白为什么抛出这个异常的原因,所以解释和解决方案会很棒!这是我在FXMLDocumentController类中的代码:

public class FXMLDocumentController implements Initializable {

    @FXML
    private ChoiceBox<?> pilot;

    public FXMLDocumentController(){  

         setMembersList();
    }


    private void setMembersList(){
        List<String> list = new ArrayList<String>();
        list.add("Item A");
        list.add("Item B");
        list.add("Item C");
        ObservableList obList = FXCollections.observableList(list);
        pilot.setItems(obList);
    }
}

这是我得到的......:

Exception in Application start method

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:483)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
    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:483)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
    at java.lang.Thread.run(Thread.java:745)

使用试验和错误时,行pilot.setItems(obList);中肯定会抛出异常,因为它在没有任何异常时启动,当我摆脱这一行时。

2 个答案:

答案 0 :(得分:1)

在调用构造函数时,FXML - 注入的ChoiceBox将不会被初始化,因此您将获得NullPointerExceptionpilotnull )。

相反,从initialize()方法调用您的代码。我还要正确输入您的ChoiceBoxObservableList

public class FXMLDocumentController {

    @FXML
    private ChoiceBox<String> pilot;

    public void initialize(){  

         setMembersList();
    }


    private void setMembersList(){
        List<String> list = new ArrayList<String>();
        list.add("Item A");
        list.add("Item B");
        list.add("Item C");
        ObservableList<String> obList = FXCollections.observableList(list);
        pilot.setItems(obList);
    }
}

答案 1 :(得分:1)

从构造函数中删除ChoiceBox对象(基本上是在FXML文件中定义的每个对象)初始化,并将其置于(最佳)initialize方法中。