• Post Reply Bookmark Topic Watch Topic
  • New Topic

KeyEvent array?  RSS feed

 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made a custom KeyListener class that I want to pass in an array of different KeyEvents that are allowed in a JTextField. When I try to compile my code, it keeps telling me I can't apply the operator == to char,java.awt.event.KeyEvent. I was looking at an example from Sun's website, and it shows me the following code

Isn't that applying the == operator to a KeyEvent?
I thought that is what I was doing, only using an array. Could someone take a look at my code and tell me what I've done wrong?
Thanks !

[ December 05, 2002: Message edited by: Jennifer Sohl ]
[ December 05, 2002: Message edited by: Jennifer Sohl ]
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look in the JavaDocs for KeyEvent KeyEvent.VK_BACK_SPACE is an int. This can be compared to a char using ==. KeyEvent.VK_BACK_SPACE is not a KeyEvent, it's just a static int in the KeyEvent class. You'll need to use the getKeyCode() or getKeyChar() methods of KeyEvent to do a comparison.
 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help. I am trying to compare ints now, but I still can't get this thing to work. I am printing to standard out the e.getKeyCode() in the keyTyped() method, and every keystroke shows it is equal to zero. In the API says keyTyped events are VK_UNDEFINED. Is this why they are all zero? Do I have to manually set the key code on them, or could I try using the keyPressed method rather than keyTyped? Would this make that much of a difference? I think I would want to stick with keyTyped()???
Thanks for any help!
[ December 11, 2002: Message edited by: Jennifer Sohl ]
[ December 11, 2002: Message edited by: Jennifer Sohl ]
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Key pressed logs every key press (i.e. if you want to type an uppercase "A", keyPressed() gets the "shift" key pressed, then the "A" key pressed), but keyTyped() only responds to events that would actually generate charaters on the screen ( i.e. it only gets an uppercase "A" - the final outcome. ).

keyPressed() can also get the key code, keyTyped() doesn't... though it doesn't look like you need the key code... just valid and invalid characters...

Something like the following...

 
Jennifer Sohl
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nathan, that worked out great!
Thank you so much for taking the time to help me.
It's nice to have my sanity back
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!