Question

I have a JTable that starts the editing automatically when pushing a key. The already inputted text will also be deleted, so that if you start typing only your typing gets the current value. That works, but my problem is, that every key starts that editing, like capslock, numlock, esc and stuff like that. How can I exclude all kind of control keys from that editing, without excluding one by one?

Here's the code I already have. It's in the Method isCellEditable in the TableCellEditor related to the table.

// 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;

}

Was it helpful?

Solution

Maybe instead of checking for false events, you shall check for positive ones:

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;
}

You may need to extend the last if list with special chars like _, *, #, etc.

OTHER TIPS

You can use the Character wrapper to easily determine what kind of key has been pushed. Methods like isLetterOrDigit(int codepoint) would probably be useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top