Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) ?

like image 546
Jalal Sordo Avatar asked Jan 18 '23 16:01

Jalal Sordo


2 Answers

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);
like image 68
trashgod Avatar answered Jan 21 '23 06:01

trashgod


Add an ActionListener to the password field component:

The code below produces this screenshot:

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);
}
like image 28
dacwe Avatar answered Jan 21 '23 05:01

dacwe