检测在JTextField中输入press [英] Detect enter press in JTextField

查看:127
本文介绍了检测在JTextField中输入press的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在java中输入JTextField时检测到有人按 Enter ?无需创建按钮并将其设置为默认值。

Is it possible to detect when someone presses Enter while typing in a JTextField in java? Without having to create a button and set it as the default.

推荐答案

A JTextField 被设计为使用 ActionListener ,就像 JButton 一样。请参阅 JTextField addActionListener()方法。

A JTextField was designed to use an ActionListener just like a JButton is. See the addActionListener() method of JTextField.

例如:

Action action = new AbstractAction()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("some action");
    }
};

JTextField textField = new JTextField(10);
textField.addActionListener( action );

现在,当使用 Enter 键时会触发事件。

Now the event is fired when the Enter key is used.

此外,即使您不想将按钮设为默认按钮,您还可以使用按钮共享监听器。

Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.

JButton button = new JButton("Do Something");
button.addActionListener( action );

注意,此示例使用 Action ,实现 ActionListener ,因为 Action 是一个具有附加功能的新API。例如,您可以禁用 Action ,这将禁用文本字段和按钮的事件。

Note, this example uses an Action, which implements ActionListener because Action is a newer API with addition features. For example you could disable the Action which would disable the event for both the text field and the button.

这篇关于检测在JTextField中输入press的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆