简体   繁体   中英

Execute login button when enter key is pressed

How can I execute my loginButton when the enter key is pressed? I tried several things but didn't work

public void actionlogin(){
    loginButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            String roosterName = loginUser.getText();
            String roosterPassw = loginPassw.getText();

            if(roosterName.equals("admin") && roosterPassw.equals("admin")) {
                Rooster gotoRooster = new Rooster();
                gotoRooster.setVisible(true);
                dispose();

            } else {

                JOptionPane.showMessageDialog(null,"Incorrect Username/Password");
                loginUser.setText("");
                loginPassw.setText("");
                loginUser.requestFocus();
            }

        }
    });
}

You can make any button the default button. The default button will be invoked when the Enter key is pressed.

When you create the button and add it to the frame you use logic like:

frame.getRootPane.setDefaultButton( loginButton );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM