Issue
I am trying to make a TableView here that when a cell's value has been modified (the user can click a cell and type a new value) if the method isValid returns false, the cell gains the invalid-cell style from the stylesheet.
Currently, the editing part works fine and isValid returns what it is supposed to according to the console output. However, the cell is not gaining the invalid-cell attribute when isValid returns false.
I know the invalid-cell style is accessible, as having column.getStyleClass().add("invalid-cell"); adds the style to the whole column, but I cannot make it so that it is just the modified cell that changes style at a time. Any ideas? Thank you.
public void loadTable(String tableName) throws SQLException {
//Clear existing columns and entries
tableView.getColumns().clear();
tableView.getItems().clear();
ObservableList<String> data = DBcontroller.getColumns(handler.getTable());
//For each column, add to table
for (int i = 0; i < data.size(); i++) {
int finalIdx = i;
TableColumn<ObservableList<String>, String> column = new TableColumn<>(data.get(i));
column.setPrefWidth(100); //Set width
//Factory (gets column data)
column.setCellValueFactory(param -> {
String cellValue = param.getValue().get(finalIdx);
return new SimpleStringProperty(cellValue);
});
//Make cells editable.
column.setCellFactory(TextFieldTableCell.forTableColumn(new DefaultStringConverter()));
column.setEditable(true);
column.setOnEditCommit(event -> {
ObservableList<String> rowData = event.getTableView().getItems().get(event.getTablePosition().getRow());
rowData.set(finalIdx, event.getNewValue());
TableCell<ObservableList<String>, String> currentCell = event.getTableColumn().getCellFactory().call(column);
if (isValid(event.getNewValue(), column.getText())) {
System.out.println("Input OK!");
currentCell.getStyleClass().remove("invalid-cell");
} else {
System.out.println("Input BAD");
currentCell.getStyleClass().add("invalid-cell");
}
});
tableView.getColumns().add(column);
}
Currently with the included code, none of the cells gain the style even when isValid returns false.
Solution
What I generally do in such cases is to put the logic in the cellFactory.
column.setCellFactory(x-> {
TableCell<EventVW, Date> cell = new TableCell<EventVW, Date>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
ObservableList<String> styleClass = getStyleClass();
styleClass.remove("err-class");
} else {
setText(item);
styleClass.remove("err-class");
if(!isValid(item)) {
styleClass.add("err-class");
}
}
}
};
So whenever the cell value is updated the style is updated too according to some function (isValid) in this example
Answered By - minus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.