Capturing global keys in Java

So, I want to trigger an event (pause / pause some media) whenever a user presses a space anywhere in my Swing application.

Since there are so many controls and panels that could focus, it is actually impossible to add all the key events to them (not to mention gross).

So i found

KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher()

which is awesome, you can register global keystroke pre-handlers. There is a big problem: spaces will be entered all the time in input fields, table cells, etc., And I obviously do not want to trigger a pause event then!

So any ideas? Perhaps there is a way to detect globally whether the cursor is focused on what allows you to enter text without having to check the list of all editable controls (vomit!)?

+3
source share
3 answers

I think you yourself answered this - yes, I think you can find out the current element that has focus, and if it is an instance of a certain class of fields, you ignore the space in order to pause the event. If he squeezes a heavy hand, do not worry, the instance is VERY fast for the JVM (and for some reason you are talking about human-scale events that are the aeon for the processor).

+2
source

Swing, , , Toolkit.addAWTEventListener KEY_EVENT_MASK, AWTEvent .

+1

... , . , ComboBoxes...

javax.swing.plaf.basic.BasicComboBoxEditor$BorderlessTextField

BorderlessTextField , , -, .

?

EDIT: , ....

 KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor() {

            public boolean postProcessKeyEvent(KeyEvent e) {
                if (e.getID() == KeyEvent.KEY_PRESSED) {
                    Object s = e.getComponent();
                    if (!(s instanceof JTextField) &&
                        !(s instanceof JTable && ((JTable) s).isEditing())
                        ) {
                        music_player.pauseEvent();
                    }

                    //System.out.println(s.getClass().toString());
                }
                return true;
            }
        });

, .   , - , - , - .

0

Source: https://habr.com/ru/post/1699154/


All Articles