java 如何使“输入”键的行为类似于在 JFrame 上提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7525061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:19:51  来源:igfitidea点击:

How to make "Enter" Key Behave like Submit on a JFrame

javaswingclient-serverjframekey-bindings

提问by Jalal Sordo

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

我想知道如何让enter-key 将登录名和密码提交到数据库(触发操作)?

回答by trashgod

One convenient approach relies on setDefaultButton(), shown in this exampleand mentioned in How to Use Key Bindings.

一种方便的方法依赖于setDefaultButton(),在本示例中显示并在如何使用键绑定中提到。

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

回答by dacwe

Add an ActionListenerto the password field component:

ActionListener向密码字段组件添加一个:

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