更改关键事件的表条目

时间:2010-11-26 09:22:39

标签: java jtable keyboard-events keycode

我有一个JTable,可以在按下键时自动开始编辑。已输入的文本也将被删除,因此如果您开始输入,只有您的输入才能获得当前值。这是有效的,但我的问题是,每个键都开始编辑,如capslock,numlock,esc和类似的东西。 如何从编辑中排除所有类型的控制键,而不是逐个排除?

这是我已有的代码。它位于与表相关的TableCellEditor中的Method 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;

}

2 个答案:

答案 0 :(得分: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;
}

您可能需要使用_,*,#等特殊字符扩展最后的 if 列表。

答案 1 :(得分:0)

您可以使用Character包装器轻松确定推送的键类型。像isLetterOrDigit(int codepoint)这样的方法可能会很有用。