aspose file tools*
The moose likes Java in General and the fly likes KeyPressed Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "KeyPressed Problem" Watch "KeyPressed Problem" New topic
Author

KeyPressed Problem

colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 744
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

Joined: Jan 29, 2003
Posts: 8791
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.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
colin shuker
Ranch Hand

Joined: Apr 11, 2005
Posts: 744
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

Joined: Jan 29, 2003
Posts: 8791
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: KeyPressed Problem