Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KeyPressed Problem

 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,

I've set up a KeyListener(have a class implementing it),
and have the keyPressed method:



However, if you press a key, and keep your finger on it, the method is continuously invoked.
Ideally I just want an action to happen once for each key press, even if the button is held down.

I thought about using a boolean keyDown, then having...



This sort of works, but I don't know if is the best way to do it

If you hold down a key, say P, this sets keyDown to false.
These printouts show, it is still reacting to the key P being down.

If you keep holding down P, then press G,
These printouts show, it is now reacting to the key G being down.

The release of G causes keyDown=false.
So then, while you still have P held down,
The printouts show, it is not reacting to this.

you can now activate another key.


This works quite well, but I can't use SHIFT+key, to activate a process,
since pressing SHIFT, causes keyDown=true.

So I would have to make modifications.
Are there better ways to achieve this??

Thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Way, way back in my Delphi and maybe PowerBuilder days, I used key-up events to drive this stuff. I really don't remember why. I do remember it was important to use mouse-up because the user might mouse-down on a button and then drag the mouse off the control as an "oops, I didn't mean to click that" gesture. I just tried that with the "Add Reply" button in my browser and it ignored the eventual mouse up off the button.
 
colin shuker
Ranch Hand
Posts: 750
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, but the keyUp / keyDown methods are deprecated.
I think I'll just have to modify the keyPressed/keyReleased code so that it doesn't react 50 times incase a key is held down.

Thanks
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd have to guess keyReleased does what I was thinking of in Key-Up. It's been a long time; I haven't actually done any of this in Java.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic