我正在尝试给我的订单一个新客户,所以我创建了一个组合框,其中有我可以选择的所有客户:
//I chose to use Customer instead of String so I can have duplicates and save the right one later
@FXML private ComboBox<Customer> selectionBox;
public void initialize() {
// Adding all customers here, simplified example:
int id = 1;
String name = "Grace";
Customer customer = new Customer(id, name);
selectionBox.getItems().add(customer);
}
这是我的客户类别的简化:
public class Customer {
private int id;
private int name;
public Customer(int id, String name) {
this.id = id;
this.name = name;
}
public String toString() {
// This is here to show the name in the ComboBox instead of 'Customer.java@37hf'
return name;
}
}
和我的订单类:
public class Order {
private int id;
private Customer customer;
public Order(int id, Customer customer) {
this.id = id;
this.customer = customer
}
public void saveSql(Customer newCustomer) {
this.customer = newCustomer;
// Sql code here
}
}
[只要我想与新客户更新订单并执行order.saveSql(selectionBox.getSelectionModel().getSelectedItem())
它给出了这个错误:Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: class java.lang.String cannot be cast to class my.package.Customer
这说明selectionBox.getSelectionModel().getSelectedItem()
是一个字符串,而日食说它是一个'客户',并且它应该是客户,因为我使用ComboBox<Customer>
初始化了ComboBox
我该怎么办?感谢您的帮助!
我正在尝试给我的订单一个新客户,所以我创建了一个可以从所有客户中选择的ComboBox://我选择使用Customer而不是String,这样我可以重复并保存正确的一个...
您会收到String
错误,因为当ComboBox
可编辑时,您正在编写的内容是TextField
,它返回了String
。当您从该字段“失去焦点”(例如,按Alt + Tab,单击其他字段等)或按“ Enter”时,系统尝试将String
添加到ComboBox
列表中,但是由于表示ComboBox
的类型为Customer
,不能。