JavaFX TableView显示空值
问题描述:
我最近遇到了一个有趣的问题。我有一个表有1个int和3个字符串列。我已经实现了对表格的过滤,除了一个小点之外,它完美地工作正常:每当至少有一个过滤结果(但少于可见行的数量)时,int列显示为空行值。如果找到的匹配数量大于可见的行数,则不会添加空值(即使使用滚动功能)。这最好与图片说明:JavaFX TableView显示空值
为不存在的值过滤器不显示空值:
FilteredList<Word> filteredData = new FilteredList<>(masterData,e->true);
SortedList<Word> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(table.comparatorProperty());
table.setItems(sortedData);
TextField filter = new TextField();
filter.setPromptText("Filter");
filter.textProperty().addListener((observableValue,oldValue,newValue)->{
filteredData.setPredicate((Predicate<? super Word>) word->{
if(word.getAllCz().toLowerCase().contains(newValue.toLowerCase()))return true;
else if(word.getAllEng().toLowerCase().contains(newValue.toLowerCase()))return true;
else if(String.valueOf(word.getUnitNo()).equals(newValue))return true;
else return false;
});
});
CellValue:
用于滤波的代码工厂:
column.setCellValueFactory(new PropertyValueFactory<>(data));
column.setCellFactory(tc-> {
TableCell<Word, Integer> cell = new TableCell<>();
Text text = new Text();
cell.setGraphic(text);
text.setTextAlignment(TextAlignment.CENTER);
text.setStyle("-fx-fill: -fx-text-background-color;");
text.setFontSmoothingType(FontSmoothingType.LCD);
text.wrappingWidthProperty().bind(column.widthProperty().subtract(5));
text.textProperty().bind(cell.itemProperty().asString());
return cell;
});
答
如果该单元是空的,它的项将是null
,和itemProperty().asString()
将评估为包含文字字“空”(类似于传递一个空值到PrintStream
)的字符串。你的绑定需要把空单元作为特殊情况:
column.setCellFactory(tc-> {
TableCell<Word, Integer> cell = new TableCell<>();
Text text = new Text();
cell.setGraphic(text);
text.setTextAlignment(TextAlignment.CENTER);
text.setStyle("-fx-fill: -fx-text-background-color;");
text.setFontSmoothingType(FontSmoothingType.LCD);
text.wrappingWidthProperty().bind(column.widthProperty().subtract(5));
text.textProperty().bind(Bindings.createStringBinding(() -> {
if (cell.isEmpty()) {
return null ;
} else {
return cell.getItem().toString();
}
}, cell.emptyProperty(), cell.itemProperty()));
return cell;
});
,或者你需要重写updateItem()
:
column.setCellFactory(tc-> {
TableCell<Word, Integer> cell = new TableCell<>() {
private Text text = new Text();
{
this.setGraphic(text);
text.setTextAlignment(TextAlignment.CENTER);
text.setStyle("-fx-fill: -fx-text-background-color;");
text.setFontSmoothingType(FontSmoothingType.LCD);
text.wrappingWidthProperty().bind(column.widthProperty().subtract(5));
}
@Override
protected void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
text.setText(null);
} else {
text.setText(item.toString());
}
}
};
return cell;
});
请包括设置第一列的cellValueFactory的代码。 – VGR
您是否在该列上有自定义单元工厂?如果是这样,请发布。另外:你是否意识到你不断地在文本字段的文本属性中添加越来越多的监听器?最终这会使应用程序停滞不前。每次文本更改时,也不需要创建新的排序列表。 –
我已经添加了一个cellValueFactory。 James_D感谢你指出了这一点..我还是新来的,所以我没有注意到。 – zotmer