我正在开发应用程序的表示层,并且遇到了 JavaFX 的“listview”的一些问题。
在应用程序的 GUI 中,我打算使用一个 ListView 元素来交替(绝不同时)显示两个不同对象的列表:“Group”类型的对象和“Expenditure”类型的对象。
当用户想要查看所有组的列表时,将调用以下函数(此处进行了简化):
private void loadGroups(){
List<Group> groups = getGroups();
ObservableList<Group> ol = FXCollections.observableList( (List<Group>)groups );
myListView.setCellFactory( new Callback<ListView<Group>, ListCell<Group>>() {
@Override
public ListCell<Group> call(ListView<Group> listView) {
return new GroupCell();
}
});
myListView.setItems(ol);
myListView.setOnMouseClicked(...);
}
双击某个组时,将执行以下代码,目的是在同一个 ListView 上显示与该组相关的所有 Expenditure 对象:
private void loadGroups(){
List<Expenditure> expenditures = getExpenditures();
ObservableList<Expenditure> ol = FXCollections.observableList( (List<Expenditure>)expenditures );
myListView.setCellFactory( new Callback<ListView<Expenditure>, ListCell<Expenditure>>() {
@Override
public ListCell<Expenditure> call(ListView<Expenditure> listView) {
System.out.println("updateView() called for expenditures.................");
return new ExpenditureCell();
}
});
myListView.setItems(ol);
myListView.setOnMouseClicked(...);
}
GroupCell 和 ExpenditureCell 对象根据以下模式重写 updateItem 方法(我将仅显示 GroupCell 对象的重写方法):
@Override
protected void updateItem(Group group, boolean empty) {
super.updateItem(group, empty);
if (empty){
setGraphic(null);
}else{
GroupCellController groupCellController = new GroupCellController();
groupCellController.setGroupInfo(group);
setGraphic(groupCellController.getAnchorPane());
//addEventFilter(MouseEvent.MOUSE_PRESSED, eve);
}
}
如果用户首先查看组列表,然后决定查看支出列表,则会发生以下错误:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: DATA.Model.Expenditure cannot be cast to DATA.Model.Group
我在这里不知所措。 CellFactories 被正确替换,可观察列表也是如此。
最佳答案
你如何声明myListView
?
我认为问题在于,当您替换单元工厂时,它会立即尝试显示当前项目,这当然是错误的类型。如果你真的想这样做,请尝试
myListView.getItems().clear();
在更换电池工厂之前。
所有这一切看起来都像是一个大黑客。一个ListView
已键入,您应该按原样使用它。您确实无法在运行时更改其类型。有什么理由不简单地切换到不同的 ListView
(即在 ListView<Group>
和 ListView<Expenditure>
之间切换,而不是仅仅重新配置单个 ListView<???>
)?
关于java - 更改项目类型时 JavaFX 中的 ListView 出现 ClassCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48243937/