我正试图给我的订单一个新客户,所以我创建了一个ComboBox,其中有我可以选择的所有客户:
//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;
}
}
我的Order类:
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>
对此我该怎么办?
感谢您的帮助!