How to find KeyCode of pressed Key

136 Views Asked by At

I would like to have 2 buttons:

1) BindBTN - When clicked a keyListener/action will listen for key press and find the KeyCode of that key.

2) RunBTN - When clicked an action will wait until the user presses the same key and then preforms runProgram()

        RunBTN.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                @SuppressWarnings("serial")
                AbstractAction run = new AbstractAction() {
                    public void actionPerformed(ActionEvent e) {
                        runProgram();
                    }
                };

                RunBTN.getInputMap().put(KeyStroke.getKeyStroke("**bound key**"),
                        "run");
                RunBTN.getActionMap().put("run",
                        run);
            }
        });

What should i do for BindBTN?

1

There are 1 best solutions below

0
FilipDolezal On

Okey so i figured it out:

for BindBTN:

        BindingBTN.addKeyListener(new KeyAdapter() 
        {
            @Override
            public void keyPressed(KeyEvent evtBind) 
            {
                BindCmd = evtBind.getKeyCode();
                BindCmdString = KeyEvent.getKeyText(BindCmd);
            }
        });

and for RunBTN:

        RunBTN.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                @SuppressWarnings("serial")
                AbstractAction run = new AbstractAction() {
                    public void actionPerformed(ActionEvent e) {
                        runProgram();
                    }
                };

                RunBTN.getInputMap().put(KeyStroke.getKeyStroke(BindCmdString),
                        "run");
                RunBTN.getActionMap().put("run",
                        run);
            }
        });