Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capturing global keypresses in Java

So I want to trigger an event (pausing/unpausing some media) whenever the user presses spacebar anywhere in the my Swing app.

Since there are so many controls and panels that could have focus, its not really possible to add keyevents to them all(not to mention gross).

So I found

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher()

which is awesome, you can register global keypress pre-handlers. There's a major problem though - spaces will be typed all the time in input fields, table cells, etc, and I obviously dont want to trigger the pause event then!

So any ideas? Perhaps there is way to detect globally whether the cursor is focused on something that allows text input, without having to check through a list of all the editable controls(vomit!)?

like image 311
dalyons Avatar asked Jul 12 '26 13:07

dalyons


2 Answers

I think you answered that yourself - yes I think you can find out the current element that has focus, and if it is an instanceof a certain field class, you ignore the space for the purpose of pause event. If it seams heavy handed, don't worry, instanceof is VERY fast for the JVM (and in any cause you are talking human scale events which are an eon to a processor).

like image 195
Michael Neale Avatar answered Jul 14 '26 04:07

Michael Neale


I'm rusty on my Swing, but I think you should try registering a global listener using Toolkit.addAWTEventListener with a KEY_EVENT_MASK. You can then filter the AWTEvent processing based on its type and source.

like image 32
ykaganovich Avatar answered Jul 14 '26 04:07

ykaganovich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!