开发者

Java KeyEvent & Syntax Highlighting

开发者 https://www.devze.com 2023-01-24 17:32 出处:网络
I\'m writing a syntax highlighting text editor in Java and I\'ve run into a bit of a problem as to what I should do as opposed to what I want to do. Basically the KeyEvent class provides me with a bit

I'm writing a syntax highlighting text editor in Java and I've run into a bit of a problem as to what I should do as opposed to what I want to do. Basically the KeyEvent class provides me with a bit of a problem:

  1. KeyTyped does not allow me to ID what the key is so it is useless for lexing.
  2. KeyPressed is better, it allows me to ID each key as it is pressed which is great for lexing, however it triggers the event before the key is actually put into the JEditorPane.
  3. KeyReleased solves the problem of both KeyPressed & KeyTyped as it occurs after the character has been input and it allows me to a开发者_开发百科ctually ID what the character is. However if I hold 'a' and it puts in 50 'a's, I'm screwed.

My solution to the issue is to use KeyPressed for all characters that are to be input, consume the event, read the character that was supposed to be input and manually input it, however I'm guessing this isn't the most elegant solution available. My question is how else could I go about this? Is there something I'm just glazing over or did I find the solution to my problem and should just roll with it?


The JavaDoc appears to be the opposite of what you say for KeyEvent:

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 should probably be using a Document Listener.

0

精彩评论

暂无评论...
验证码 换一张
取 消