How to make “Enter” Key Behave like Submit on a JF

2019-05-07 01:58发布

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

2条回答
欢心
2楼-- · 2019-05-07 02:09

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);
查看更多
一夜七次
3楼-- · 2019-05-07 02:24

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);
}
查看更多
登录 后发表回答