【问题标题】:How to make "Enter" Key Behave like Submit on a JFrame如何使“Enter”键的行为类似于在 JFrame 上提交
【发布时间】:2011-09-23 06:22:35
【问题描述】:

我正在构建一个客户端/服务器应用程序。 我想让用户在身份验证框架上更容易。

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

【问题讨论】:

    标签: java swing client-server jframe key-bindings


    【解决方案1】:

    一种方便的方法依赖于setDefaultButton(),在此example 中显示并在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);
    

    【讨论】:

    • +1,我喜欢这种将 ActionListener 添加到按钮的解决方案,这样当按下回车键时,哪个文本字段具有焦点就无关紧要了。
    【解决方案2】:

    在密码字段组件中添加ActionListener

    下面的代码产生了这个截图:

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

    【讨论】:

    • 为什么ActionListener只添加到密码字段?如果用户跳回名称字段并输入怎么办?
    • @camickr: ?有两个动作监听器?而且,这只是一个如何使用它们的例子..
    • 将其重新分解为单个常见的Action 可能会很有用。也可以考虑JPasswordField
    • 糟糕,错过了第二个 Action,因为问题是关于如何在 Enter 键上提交数据(而不是关于如何编写 ActionLister)。我试图强调 Action 属于一个按钮,而不是文本字段。正常的 UI 是有一个(或两个)按钮来处理数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2010-11-03
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多