I have a table column with datatype Integer. i want to make this column editable without changing the datatype to String anywhere. I used textfieldtablecell but it commits value only on pressing enter. So i want some other method. Please suggest something. To make it [possible I have done something like this. But my cell is not becoming editable.
public class EditCell implements initializable{
@FXML
private TableView<ResourceMaster> roletable;
@FXML
private TableColumn<ResourceMaster, Integer> loadedHrs;
@Override
public void initialize(URL location, ResourceBundle resources) {
Callback<TableColumn<ResourceMaster,Integer>, TableCell<ResourceMaster,Integer>> txtCellFactory =
(TableColumn<ResourceMaster,Integer> p) -> {return new EditingCell();};
loadedHrs.setCellFactory(txtCellFactory);
}
public class EditingCell extends TableCell<ResourceMaster, Integer> {
private TextField textField;
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
if (textField == null) {
createTextField();
}
// setText(null);
commitEdit(Integer.valueOf((textField.getText())));
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
textField.requestFocus();
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(String.valueOf(getItem()));
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
@Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
//setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(String.valueOf(getString()));
}
setGraphic(textField);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
setText(String.valueOf(getString()));
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}
private void createTextField() {
textField = new TextField(String.valueOf(getString()));
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(Integer.valueOf(textField.getText()));
EditingCell.this.getTableView().requestFocus();//why does it lose focus??
EditingCell.this.getTableView().getSelectionModel().selectBelowCell();
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode().isDigitKey()) {
if (CellField.isLessOrEqualOneSym()) {
CellField.addSymbol(t.getText());
} else {
CellField.setText(textField.getText());
}
textField.setText(CellField.getText());
textField.deselect();
textField.end();
textField.positionCaret(textField.getLength() + 2);//works sometimes
}
}
});
}
private Integer getString() {
return getItem();
}
}
}