Java - Adding keyboard shortcut for JButton

239 views Asked by At

I'm trying to add an accelerator/keyboard shortcut to a JButton in a GUI in Eclipse (Luna).

I'm trying to replicate what the program would do when a "Login" button is pressed, but I also want it to work when the "Enter" key on the keyboard is pressed.

I've tried "Add event handler > key > KeyPressed" for the JButton and even tried the JPasswordField/JTextField, but then the code I try doesn't end up working.

This is the auto-generated code for the GUI elements:

    loginButton = new JButton("Login");
    loginButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            checkPassword();
        }

    });
    loginButton.setBounds(146, 117, 165, 23);
    frmIpassAccountManager.getContentPane().add(loginButton);

I've spent a fair amount of time searching Stackoverflow and other websites for a solution but am yet to find a solution. I've added accelerators to JMenuItems before, but I believe it works differently to JButtons, ect.

If some one could please tell me what code to add to which GUI element that would be extremely helpful.

Thank you.

0

There are 0 answers