4

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Jalal Sordo
  • 1,605
  • 3
  • 41
  • 68

2 Answers2

7

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);
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • +1, I like this solution of adding the ActionListener to the button so that it doesn't matter which text field has focus when the enter key is pressed. – camickr Sep 23 '11 at 15:32
2

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);
}
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • Why is the ActionListener only added to the password field? What if the user tabs back to the name field and users enter? – camickr Sep 23 '11 at 15:31
  • @camickr: ? There are two action listeners? And also, this was just an example how to use them.. – dacwe Sep 23 '11 at 15:45
  • It might be useful to re-factor this into a single, common `Action`. Also consider `JPasswordField`. – trashgod Sep 23 '11 at 15:49
  • Oops, missed the second Action because the question was about how to submit the data on an Enter key (not on how to write an ActionLister). I was trying to stresss that the Action belongs to a button, not the text fields. The normal UI is to have a button (or two) to process data. – camickr Sep 23 '11 at 16:05