aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes JSpinner and KeyListener: not working Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JSpinner and KeyListener: not working" Watch "JSpinner and KeyListener: not working" New topic
Author

JSpinner and KeyListener: not working

David A. Smith
Greenhorn

Joined: Sep 08, 2010
Posts: 9

I've created a number-spinner class which should allow the user to press the + or - keys to increment or decrement the value. This is in addition to the normal up and down arrows on the control. (The idea is to have - another - keyboard control for changing the value.)

I've tried several variations, but can't seem to get the key handler to even be invoked. I've searched in this forum and elsewhere and have found a couple of similar descriptions, with responses like "oh yeah, it works now" (without much substance). Unfortunately, I still haven't reached that "oh yeah" part yet. Any ideas?

Thanks in advance...

I've extracted everything down to the smallest possible (and still broken) stand-alone example. Here's the code:

Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4658
    
    5

This makes use of the key bindings of the arrow keys and binds them to the numpad + and - keys. It's also necessary to consume the key typed events so that they aren't echoed in the spinner's editor.

I prefer to not extend Swing components (any class, really!) except where absolutely necessary, and favor a static utility method that returns a customized component.

edit: I'm not sure whether it's documented that listeners are invoked in the reverse of the order in which they are added, but AFAIK that's the behavior for all listeners added to Swing components, and this solution depends on it so as to consume the key typed events before they are processed by the UI-installed handler.


luck, db
There are no new questions, but there may be new answers.
David A. Smith
Greenhorn

Joined: Sep 08, 2010
Posts: 9

Very interesting...! Thanks for your reply. I'm not familiar with the particular technique, so I'll have to play with it a bit.

Also, thanks for your comment on the order of listeners. I had wondered about that, but hadn't watched it that closely. I had another problem where I was trying to temporarily take listeners out of the loop so I could programatically set values without firing events to the listeners, but that's a different topic.

Dave.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4658
    
    5

I'm not familiar with the particular technique, so I'll have to play with it a bit.

How to use Key Bindings
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JSpinner and KeyListener: not working