我有一个侦听键盘事件的事件侦听器。当我尝试通过使用键盘事件进入编辑模式时,出于某种奇怪的原因,不正确的单元格进入编辑模式。TableView - 编辑聚焦单元格
例如,我想编辑一个单元格。我使用键盘箭头前往我想要编辑的单元格,即聚焦的单元格。通过点击键盘上的一个字母,聚焦的单元格应该进入编辑模式。当我尝试编辑聚焦的单元格时,错误的单元格进入编辑模式。
private final class EditCell extends TableCell<SimpleStringProperty, String> implements GenericTable
{
public EditCell()
{
// Add event listsner. table is a TableView
table.setOnKeyPressed(keyEvent -> this.handleKeyPressed(keyEvent));
}
public void handleKeyPressed(KeyEvent key)
{
// Keyboard events
if (key.getCode().isLetterKey())
{
if (!this.isEditing())
{
this.edit = true;
// focus index
int focusIndex = this.table.getSelectionModel().getFocusedIndex();
this.changeTableCellFocus(this.table, focusIndex);
this.startEdit();
}
}
}
// startEdit() function
@Override
public void startEdit()
{
if (this.edit)
{
LOGGER.info("Start editing on cell index: " + this.getIndex());
super.startEdit();
this.createTextField();
this.setText(null);
this.setGraphic(this.textField);
this.textField.selectAll();
this.textField.requestFocus();
this.textField.setOnKeyPressed(keyEvent -> this.handleKeyPressed(keyEvent));
this.textField.focusedProperty()
.addListener((observable, oldValue, newValue) -> this.onTextFieldFocusChange(observable,
oldValue,
newValue));
}
}
// Change focus
public void changeTableCellFocus(final TableView<?> table, final int focusIndex)
{
table.requestFocus();
table.getSelectionModel().clearAndSelect(focusIndex);
table.getFocusModel().focus(focusIndex);
}
}
在进入编辑模式之前,我将焦点更改为单击的单元格,然后调用startEdit()方法。我试图调试这个问题,但没有运气。我注意到focusIndex与当前单元格索引不同。我不确定为什么指数是不同的。
你可以给这个代码一些上下文吗?这是在'TableCell'子类中? – 2015-02-11 14:08:15
你是否尝试使用选择而不是焦点?我猜表格编辑是基于选择而不是焦点。 – eckig 2015-02-11 14:17:06
changeTableCellFocus(...)函数选择单元格+将焦点放在单元格上。你的意思是,只要选择单元格,然后调用startEdit()。我认为问题在于当前单元格索引与焦点单元格索引不同,这意味着即使将所选单元格更改为焦点索引单元格,仍然会遇到问题,因为在当前单元格中调用了startEdit()。 – breaktop 2015-02-11 14:26:45