我在向 TableView 插入元素时遇到问题。
我从 Node 获得了 tableview 的引用。问题是我在向表中插入元素时遇到错误。
The method add(capture#2-of ?) in the type List<capture#2-of ?> is not applicable for the arguments
TableView<?> table = (TableView<?>)mainPane.getChildren().stream().filter(c -> c instanceof TableView<?>).findFirst().get();
ControlTimePickerController ctpc = new ControlTimePickerController();
if (ctpc.exitedWithButton()) {
ControlSchedule cSch = ctpc.getSelectedControlSchedule();
//I'M GETTING THE ERROR HERE
table.getItems().add(cSch);
}
最佳答案
您需要使用另一个类型参数来指示 ControlSchedule
确实是可以添加到 items
的类型列出或使用原始类型。后一种方法与使用 TableView<Object>
具有类似的效果。在这种情况下。然而,不鼓励使用原始类型;在这种情况下,无论如何你已经把类型安全抛到了窗外。
这里我建议使用
TableView<? super ControlSchedule> table = (TableView<? super ControlSchedule>)mainPane.getChildren().stream().filter(c -> c instanceof TableView<?>).findFirst().get();
但是你需要 100% 确定这个 Actor 不会破坏任何东西。有很多对象用于设置 TableView
如果 TableView
的类型,则可能会导致异常实际上与 table
声明中使用的类型参数不匹配上面的变量。
无论如何我不建议使用这种代码。更好的替代方案是使用合适的数据结构来存储 TableView
(s)。这将允许您通过允许编译器进行检查来避免这种类型的强制转换。
关于JavaFX 将问号 TableView 转换为已知类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58484941/