對不起,如果這已被回答,我試圖尋找解決方案,但我找不到任何相關的東西。我對此很陌生,所以有機會我完全忽略或忽略了一些可以讓我獲得簡單解決方案的東西。Swing JTable - 在Shift鍵上使用鍵綁定代替KeyListener
我已經爲Shift鍵實現了一個按鍵監聽器,這樣當用戶按下shift鍵時,他會進入編輯更多的單元格(請看下面的代碼)。雖然有一個問題,如果用戶當前正在向單元格輸入數據,則shift鍵不起作用,並且在調試時,我們可以看到程序甚至從未進入關鍵字偵聽器。我被告知使用鍵綁定而不是鍵監聽器來解決這個問題。我試圖在線上學習一些教程,看起來我失敗了。任何幫助將非常感謝,非常感謝!
兩個關鍵聽衆(表工作正常,而Shift鍵不):
table.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
//KeyCode 9 is a key code for the Tab key
if (e.getKeyCode() == 9) {
if(table.isCellEditable(table.getSelectedRow(),table.getSelectedColumn())) {
table.editCellAt(table.getSelectedRow(), table.getSelectedColumn());
} else {
table.editCellAt(table.getSelectedRow(), table.getSelectedColumn() + 1);
}
}
//The problem occurs here
//KeyCode 16 is a key code for the Shift key
if (e.getKeyCode() == 16) {
if(table.isCellEditable(table.getSelectedRow() + 1, table.getSelectedColumn())) {
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
} else {
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn() + 1);
table.setColumnSelectionInterval(table.getSelectedColumn() + 1, table.getSelectedColumn() + 1);
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
}
}
}
});
這裏是我的嘗試(和失敗)解決方案:
class ShiftAction extends AbstractAction{
public void actionPerformed(ActionEvent ae){
System.out.println("Shift");
table.editCellAt(table.getSelectedRow() + 1, table.getSelectedColumn());
table.setColumnSelectionInterval(table.getSelectedColumn(), table.getSelectedColumn());
table.setRowSelectionInterval(table.getSelectedRow() + 1, table.getSelectedRow() + 1);
}
}
shiftAction = new ShiftAction();
table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT,KeyEvent.SHIFT_DOWN_MASK),"doShiftAction");
table.getActionMap().put("doShiftAction",shiftAction);
希望這個問題不是太傻了,一旦再次,在此先感謝。
「我被告知使用鍵綁定而不是鍵監聽器來解決這個問題。」:由誰?去問問他們。這不會解決您的問題,但會增加您的問題(正如您現在正確地看到的那樣) – gpasch
我的Java教師告訴我這樣做沒有太多時間來幫助我(我還剩下幾天時間我必須完成這個項目)。這不是什麼大不了的事情,我可以保持原樣,這對我來說更像是一種學習體驗。 –
@ gpasch,是的,鍵綁定是更好的解決方案。它是一個更新,更好的API,解決了焦點問題。 – camickr