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) ?
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);
Add an ActionListener to the password field component:
The code below produces this screenshot:

public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(2, 2));
    final JTextField user = new JTextField();
    final JTextField pass = new JTextField();
    user.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            pass.requestFocus();
        }
    });
    pass.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String username = user.getText();
            String password = pass.getText();
            System.out.println("Do auth with " + username + " " + password);
        }
    });
    frame.add(new JLabel("User:"));
    frame.add(user);
    frame.add(new JLabel("Password:"));
    frame.add(pass);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With