FilipDolezal
FilipDolezal

Reputation: 71

How to find KeyCode of pressed Key

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?

Upvotes: 0

Views: 138

Answers (1)

FilipDolezal
FilipDolezal

Reputation: 71

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);
            }
        });

Upvotes: 0

Related Questions