【发布时间】:2021-10-17 16:15:54
【问题描述】:
我是 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"; 一切正常,除了我的 ComboBox 填充了“A”而不是游戏名称。并且更改值工作得很好(我得到了正确的getId() 值)。
有什么想法吗?
【问题讨论】: