我学习使用JavaFX UI控件Example 12-12 Adding Map Data to the Table
它在java中的作用:
TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");
firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
firstDataColumn.setMinWidth(130);
secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
secondDataColumn.setMinWidth(130);
TableView table_view = new TableView<>(generateDataInMap());
table_view.setEditable(true);
table_view.getSelectionModel().setCellSelectionEnabled(true);
table_view.getColumns().setAll(firstDataColumn, secondDataColumn);
Callback<TableColumn<Map, String>, TableCell<Map, String>>
cellFactoryForMap = new Callback<TableColumn<Map, String>,
TableCell<Map, String>>() {
@Override
public TableCell call(TableColumn p) {
return new TextFieldTableCell(new StringConverter() {
@Override
public String toString(Object t) {
return t.toString();
}
@Override
public Object fromString(String string) {
return string;
}
});
}
};
firstDataColumn.setCellFactory(cellFactoryForMap);
secondDataColumn.setCellFactory(cellFactoryForMap);
但是这部分在kotlin中不起作用(转换后):
val cellFactoryForMap =
object : Callback<TableColumn<Map<*, *>, String>, TableCell<Map<*, *>, String>> {
override fun call(p: TableColumn<*, *>): TableCell<*, *> {
return TextFieldTableCell(object : StringConverter() {
override fun toString(t: Any): String {
return t.toString()
}
override fun fromString(string: String): Any {
return string
}
})
}
}
错误:(49,33)Kotlin:对象必须声明为抽象或实现抽象成员公共抽象乐趣调用(p0:TableColumn&gt;,String&gt;!):TableCell,*&gt ;, String&gt;!在javafx.util.Callback中定义
错误:(50,13)Kotlin:'call'取代任何内容
错误:(51,24)Kotlin:类型推断失败:构造函数TextFieldTableCell(p0:StringConverter!) 无法应用 ()
错误:(51,43)Kotlin:类型不匹配:推断类型是但StringConverter&lt;(??? ??? ???)&gt;!预计
错误:(51,52)Kotlin:javafx.util中定义的StringConverter类的一个类型参数
错误:(52,21)Kotlin:'toString'覆盖任何内容
错误:(56,21)Kotlin:'fromString'覆盖任何内容
如何编写正确的代码?
答案 0 :(得分:1)
TextFieldTableCell中的类型错误。
仔细查看TextFieldTableCell<S,T> extends TableCell<S,T>
和方法TextFieldTableCell(StringConverter<T> converter)
如果回调返回类型为TableCell<Map<*, *>, String>>
,则字符串转换器必须为StringConverter<String>
才能满足类型约束。
Callback<TableColumn<Map<*, *>, String>, TableCell<Map<*, *>, String>> {
TextFieldTableCell(object: StringConverter<String>() {
override fun fromString(string: String): String {
return string
}
override fun toString(`object`: String): String {
return `object`
}
})
}