我有一個偵聽鍵盤事件的事件偵聽器。當我嘗試通過使用鍵盤事件進入編輯模式時,出於某種奇怪的原因,不正確的單元格進入編輯模式。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