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

≯℡__Kan透↙ 提交于 2019-12-05 13:34:37
trashgod

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