用户按下进入Java时检测 [英] Detecting when user presses enter in Java

查看:135
本文介绍了用户按下进入Java时检测的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JComboBox的子类。我尝试添加以下代码的密钥监听器。

 

addKeyListener(new KeyAdapter
{
public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode()== KeyEvent.VK_ENTER)
{
System.out .println(Pressed);
}
}
});

然而,这并不能正确地检测用户按下键的时间。其实根本不叫。我添加这个听众错了吗?有没有其他方法可以添加?

解决方案

关键事件不会在盒子本身而是其编辑器上触发。您需要将keyListener添加到JComboBox的编辑器中,而不是直接添加:

  comboBox.getEditor()。getEditorComponent ).addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent evt)
{
if(evt.getKeyCode()== KeyEvent.VK_ENTER)
{
System.out.println(Pressed);
}
}
});

编辑:固定方法调用。


I have a subclass of JComboBox. I attempt to add a key listener with the following code.


        addKeyListener(new KeyAdapter() 
        {
            public void keyPressed(KeyEvent evt)
            {
                if(evt.getKeyCode() == KeyEvent.VK_ENTER)
                {
                    System.out.println("Pressed");
                }
            }
        });

This however does not correctly detect when the user presses a key. It is actually not called at all. Am I adding this listener wrong? Are there other ways to add it?

解决方案

Key events aren't fired on the box itself, but its editor. You need to add the keyListener to the editor of the JComboBox and not the box directly:

comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() 
    {
        public void keyPressed(KeyEvent evt)
        {
            if(evt.getKeyCode() == KeyEvent.VK_ENTER)
            {
                System.out.println("Pressed");
            }
        }
    });

Edit: fixed method call.

这篇关于用户按下进入Java时检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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