2010-11-26 36 views
0

我有一個JTable,當按下一個鍵時會自動開始編輯。已經輸入的文本也會被刪除,所以如果你開始輸入,只有你的輸入得到當前值。這是有效的,但我的問題是,每個鍵開始編輯,像capslock,numlock,esc和類似的東西。 如何從該編輯中排除所有類型的控制鍵,而無需一一排除?更改關鍵事件表條目

這裏是我已經有的代碼。它位於與表格相關的TableCellEditor中的isCellEditable方法中。

// It's a keyevent, so check if it's a key that should start editing 
if (anEvent instanceof KeyEvent) { 

// Get the events key 
int keyCode = ((KeyEvent) anEvent).getKeyCode(); 
char keyChar = ((KeyEvent) anEvent).getKeyChar(); 

// Convert character to lower case by first creating a string out of it 
keyChar = ("" + keyChar).toLowerCase().charAt(0); 

// F2 allowed 
if (keyCode == KeyEvent.VK_F2) { 
    return true; 
} 

// Keycode is unknown so check if we can at least find the keyChar 
if (keyCode == 0 && (keyChar == 'ä' || keyChar == 'ö' || keyChar == 'ü')) { 
    resetText = true; 
    return true; 
} 

// Control characters disallowed 
if (keyCode < 32 || keyCode == KeyEvent.VK_WINDOWS 
     || keyCode == KeyEvent.VK_CONTEXT_MENU || keyCode == KeyEvent.VK_SCROLL_LOCK 
     || keyCode == KeyEvent.VK_NUM_LOCK || keyCode == KeyEvent.VK_META 
     || (keyCode >= KeyEvent.VK_F1 && keyCode <= KeyEvent.VK_F12)) 
    return false; 

// all other keys are allowed 
resetText = true; 
return true; 

}

回答

1

也許,而不是檢查錯誤的事件,您應積極的檢查:

if (anEvent instanceof KeyEvent) { 
    // Get the events key 
    int keyCode = ((KeyEvent) anEvent).getKeyCode(); 
    char keyChar = ((KeyEvent) anEvent).getKeyChar(); 
    resetText = false; 
    // F2 allowed 
    if (keyCode == KeyEvent.VK_F2) { 
     return true; 
    } 
    // letters, digits and space allowed 
    if (Character.isSpaceChar(keyChar) || Character.isLetterOrDigit(keyChar)) { 
     resetText = true; 
     return true; 
    } 
    return false; 
} 

您可能需要使用特殊字符像延長最後如果列表_ ,*,#等

+0

太好了,謝謝。這將工作正常。 – multiholle 2010-11-26 13:59:44

0

您可以使用字符包裝來輕鬆確定已推送哪種類型的密鑰。像isLetterOrDigit(int codepoint)這樣的方法可能會有用。