我为TableView定义了自己的可编辑单元格。一切都很好,但我希望能够通过单元格切换。假设我在单选按钮上的单元格[2,2]中我希望所选单元格转到[3,2]。这可能吗?我该如何实现这一目标?我应该向TableCell或TableColumn添加一个监听器吗?
这是我的自定义TableCell
class EditingCell extends TableCell<Student, String> {
private TextField textField;
public EditingCell(Assignment assign) {
this.setTooltip(new Tooltip(assign.getMaxPoints() + " pts max"));
}
@Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
@Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
@Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
答案 0 :(得分:4)
您可以通过向textField
添加KeyListener来实现此目的。尝试将以下代码添加到createTextField()
textField.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(Integer.parseInt(textField.getText()));
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitEdit(Integer.parseInt(textField.getText()));
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(), nextColumn);
}
}
}
});
还有一些事情你需要照顾。有关完整示例,请按照