gpt4 book ai didi

java - 尝试使用 javafx 将项目分配给选择框时出现 InspirationTargetException

转载 作者:行者123 更新时间:2023-12-02 05:34:37 25 4
gpt4 key购买 nike

向我的选择框添加选项的简单尝试会导致 InitationTargetException。我真的不明白抛出这个异常的原因,所以解释和解决方案会很棒!这是我在 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); 行中抛出,因为当我摆脱此行时,它会启动而没有任何异常。

最佳答案

您的 FXML 注入(inject)的 ChoiceBox 在调用构造函数时不会被初始化,因此您将得到一个 NullPointerException (pilotnull)。

相反,从 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 将项目分配给选择框时出现 InspirationTargetException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25136692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com