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

心已入冬 提交于 2019-12-07 08:46:00

问题


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


回答1:


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



回答2:


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);
}


来源:https://stackoverflow.com/questions/7525061/how-to-make-enter-key-behave-like-submit-on-a-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!