InvocationTargetException

InvocationTargetException

将选项添加到“我的选择”框中的简单尝试将导致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);行中引发,因为当我摆脱该行时,它在启动时没有任何异常。

最佳答案

注入了FXMLChoiceBox在构造函数被调用时不会被初始化,因此您将得到一个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);
    }
}

关于java - 尝试使用javafx将项目分配给选择框时InvocationTargetException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25136692/

10-08 21:16