我正在尝试在TableView中实现微调器编辑器。我在这个主题上看到了各种StackOverflow,但似乎没有一个能解决这个问题。
我创建了从TableCell扩展的类。创建微调器和所有内容,我只是不能让微调器提交编辑。
private final class SpinnerCell extends TableCell<Car, Integer> {
private final ScrollSpinner<Integer> spinner;
private SpinnerCell(int min, int max, int initial, int step) {
spinner = new ScrollSpinner<>();
spinner.setValueFactory(new IntegerSpinnerValueFactory(min, max, initial, step));
setEditable(true);
}
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
spinner.getValueFactory().setValue(getItem());
setOnKeyTyped(event -> { //I tried spinner.setOnKeyTyped, spinner.getEditor().setOnKeyTyped with no luck
if (event.getCode() == KeyCode.ENTER) {
Log.debug("commiting");
commitEdit(spinner.getValue()); //FIXME Never commited
}
});
setText(null);
setGraphic(spinner);
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().toString());
setGraphic(null);
}
@Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setText(null);
setGraphic(spinner);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
}
}
答案 0 :(得分:2)
您必须将onKeyTyped
更改为onKeyPressed
。您还必须将commitEdit
电话打包在Platform.runLater
。
private final class SpinnerCell extends TableCell<Car, Integer> {
private final ScrollSpinner<Integer> spinner;
private SpinnerCell(int min, int max, int initial, int step) {
spinner = new ScrollSpinner<>();
spinner.setValueFactory(new IntegerSpinnerValueFactory(min, max, initial, step));
setEditable(true);
}
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
spinner.getValueFactory().setValue(getItem());
setOnKeyPressed(event -> {
if (event.getCode() == KeyCode.ENTER) {
Platform.runLater(() -> {
commitEdit(spinner.getValue());
});
}
});
setText(null);
setGraphic(spinner);
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().toString());
setGraphic(null);
}
@Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setText(null);
setGraphic(spinner);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
}