Search code examples
javaswingclient-serverjframekey-bindings

How to make "Enter" Key Behave like Submit on a JFrame


I'm Building a Client/Server application. and I want to to make it easy for the user at the Authentication Frame.

I want to know how to make enter-key submits the login and password to the Database (Fires the Action) ?


Solution

  • One convenient approach relies on setDefaultButton(), shown in this example and mentioned in How to Use Key Bindings.

    JFrame f = new JFrame("Example");
    Action accept = new AbstractAction("Accept") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            // handle accept
        }
    };
    private JButton b = new JButton(accept);
    ...
    f.getRootPane().setDefaultButton(b);