0

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.

James M
  • 1
  • 2
  • Read the documentation: https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html – mr mcwolf May 24 '15 at 04:22
  • 1
    See [JRootPane#setDefaultButton](http://docs.oracle.com/javase/7/docs/api/javax/swing/JRootPane.html#setDefaultButton(javax.swing.JButton)) – MadProgrammer May 24 '15 at 04:57
  • I've read all that stuff already... pretty much everything has a different method on how to do it, and half are different to what I'm doing. Could some kind person actually be helpful and help a noob here? – James M May 24 '15 at 06:14
  • `I've read all that stuff already... ` - then you have your answer. If you have problems then post your [SSCCE](http://sscce.org/) that demonstrates the problem. We can't guess what you find confusing. Why do you think the examples we might post will be any different that the examples you have already found??? – camickr May 24 '15 at 17:54

0 Answers0