java在JavaFX中将项目添加到ComboBox时出现问题
我是JavaFX的新手,尝试从窗口应用程序开始。首先,我有一个简单的ComboBox
,我用游戏类型填充它,选择一种。没有更多的开始。于是问题开始了。根据this answer,我创建了一个模型类,用于在ComboBox
中输入值。但是,当应用程序启动时,出现一个错误:
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at
com.vojjin.pcreator@1.1/com.vojjin.pcreator.HelloController$1.toString(HelloController.java:23)
这是一个窗口,只有一个Label
和ComboBox
:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.effect.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<Pane prefHeight="250.0" prefWidth="654.0" xmlns="http://javafx.com/javafx/11.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.vojjin.pcreator.HelloController">
<padding>
<Insets bottom="20.0" left="20.0" right="20.0" top="20.0" />
</padding>
<Label layoutX="7.0" layoutY="2.0" prefHeight="17.0" prefWidth="94.0" text="Select game type" />
<ComboBox fx:id="gameTypeCombo" layoutX="7.0" layoutY="20.0" prefWidth="150.0" />
</Pane>
以下是模型类:
package com.vojjin.pcreator.items;
public class GameType {
private final String name;
private final String id;
public GameType(String name, String id) {
this.name = name;
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
和控制器类(其中我收到一个错误):
package com.vojjin.pcreator;
import com.vojjin.pcreator.items.GameType;
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.util.StringConverter;
public class HelloController {
private String gameType;
@FXML
private ComboBox<GameType> gameTypeCombo;
public void initialize() {
StringConverter<GameType> t=new StringConverter<>() {
@Override
public String toString(GameType object) {
return object.getName(); //this is the error line
}
@Override
public GameType fromString(String string) {
return null;
}
};
gameTypeCombo.setConverter(t);
gameTypeCombo.setItems(FXCollections.observableArrayList(
new GameType("Arithmo Games", "arithmo"),
new GameType("iMath Games", "imath")
));
gameTypeCombo.valueProperty().addListener((obs, oldVal, newVal) -> {
gameType = newVal.getId();
System.out.println(gameType);
});
}
}
行:return object.getName();
正在生成错误。这一行应该显示在ComboBox
中。例如,如果我把return "A";
放进去,所有东西都在工作,除了我的组合框用“A”而不是游戏名填充。而且更改值的效果很好(我得到了合适的getId()
值)
有什么想法吗
# 1 楼答案
当初始化
Combobox
且未选择任何值时public String toString(GameType object)
中的object
为空public String toString(GameType object)
必须修改以处理空对象例如:
或
或者,您可以在初始化组合时选择一个值:
gameTypeCombo.getSelectionModel().select(0);