有点晚了,但这是我的解决方案(确保它不是“最佳实践”,但对我有用,到目前为止我还没有找到更好的方法)以防钢铁需要它。这只是一些部分:我认为在这种情况下更容易理解。请注意,该列不可编辑。为了使其可编辑,您需要在“return new TableCell()”中重写方法“startEdit”、“cancelEdit”和“commitEdit”(它不在这个问题主题中)。
@FXML private TableView<YourEntity> table;
@Override
@SuppressWarnings("unchecked")
public void initialize(URL location, ResourceBundle resources) {
TableColumn column1 = new TableColumn(resources.getString("YourShowedColumnName"));
column1.setCellValueFactory(new PropertyValueFactory<>("YourDBColumnName"));
table.getColumns().setAll(column1, ..., .......);
table.setFixedCellSize(20.0); //To not change it in "graphic" with TextFlow
column1.setCellFactory(column -> {
return new TableCell<Mandant, String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item == null || empty) {
setGraphic(null);
setText(null);
setStyle("");
} else {
setGraphic(null);
if (!searchField.getText().isEmpty() && item.toLowerCase().contains(searchField.getText().toLowerCase())) {
Double rowHeight = this.getTableRow().getHeight();
setGraphic(buildTextFlow(item, searchField.getText()));
setHeight(rowHeight);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
setText(item);
setTextFill(Color.BLACK);
setStyle("");
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
};
table.setEditable(true);
/**
* Build TextFlow with selected text. Return "case" dependent.
*
* @param text - string with text
* @param filter - string to select in text
* @return - TextFlow
*/
private TextFlow buildTextFlow(String text, String filter) {
int filterIndex = text.toLowerCase().indexOf(filter.toLowerCase());
Text textBefore = new Text(text.substring(0, filterIndex));
Text textAfter = new Text(text.substring(filterIndex + filter.length()));
Text textFilter = new Text(text.substring(filterIndex, filterIndex + filter.length())); //instead of "filter" to keep "case"
textFilter.setFill(Color.ORANGE);
textFilter.setFont(Font.font("Helvetica", FontWeight.BOLD, 12));
return new TextFlow(textBefore, textFilter, textAfter);
}
希望它对某人有帮助。