Search code examples
javafxkeystroke

How to trigger an event in a JavaFX Application (Stage) when some keys are pressed on the KeyBoard?


I'm trying to setup a backdoor on an application which I'm working on.

I want to load a new Window when the user presses "CTRL + ALT + F12". This is what I have tried so far though it is terribly bad.

//packages
import java.awt.EventQueue;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;

//...
private void setupBackPass(){
        HashMap<KeyStroke, Action> actionMap = new HashMap<KeyStroke, Action>();
        KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.ALT, KeyEvent.CTRL_DOWN_MASK);
        actionMap.put(key1, new AbstractAction("action1") {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Ctrl-ALT pressed: " +e);
            }
        });


        KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        kfm.addKeyEventDispatcher(new KeyEventDispatcher() {
            @Override
            public boolean dispatchKeyEvent(KeyEvent e) {
                KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
                if(actionMap.containsKey(keyStroke)){
                final Action a = actionMap.get(keyStroke);
                final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null);
                EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {

                }
                });

                return false;
                }
            });
        });


    }


Am not sure how to do it but I would like it that if the keys are pressed then a Super admin window should be opened.


Solution

  • From the code you posted, it looks like you are using Swing and not JavaFX. It also looks like you are trying to use Key Bindings. As explained in that link, you need to modify both the input map and the action map. Also, you don't create an action map, you use the existing one. Again, that is explained in the page that I provided a link to.