How to detect backspace in a keyTypedEvent

后端 未结 2 820
别那么骄傲
别那么骄傲 2020-12-20 03:35

I\'m using Netbeans\' bean form to create my GUI.
I\'ve added a keyTyped event to a JTextArea and I want to detect if the typed key is a Backspace.

I\'

2条回答
  •  半阙折子戏
    2020-12-20 04:12

    backspace and delete have the following constants:

    VK_BACK_SPACE

    VK_DELETE

    Constants are listed here: Class KeyEvent

    From docs.oracle.com

    WARNING: Aside from those keys that are defined by the Java language (VK_ENTER, VK_BACK_SPACE, and VK_TAB), do not rely on the values of the VK_ constants. Sun reserves the right to change these values as needed to accomodate a wider range of keyboards in the future.

    Aside from that, I suggest you use keyPressed() or keyReleased() since keyTyped() is only used for keys that produce characters. Keys backspace and delete do not produce characters.

    Additional:

    getKeyChar() works well with KEY_TYPED, as mentioned here:

    The getKeyChar method always returns a valid Unicode character or CHAR_UNDEFINED. Character input is reported by KEY_TYPED events: KEY_PRESSED and KEY_RELEASED events are not necessarily associated with character input.

    Therefore, the result of the getKeyChar method is guaranteed to be meaningful only for KEY_TYPED events.

    You can take a look at these links:

    The keyTyped() event is only used for keys that produce character input.

    "Key typed" events are higher-level and generally do not depend on the platform or keyboard layout.

提交回复
热议问题