JFrame没有响应的KeyListener [英] Unresponsive KeyListener for JFrame

查看:92
本文介绍了JFrame没有响应的KeyListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的 JFrame 实现 KeyListener 。在构造函数上,我正在使用此代码:

I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:

System.out.println("test");
addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) { System.out.println( "tester"); }

    public void keyReleased(KeyEvent e) { System.out.println("2test2"); }

    public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
});

当我运行它时, test 消息进入我的控制台。但是,当我按下一个键时,我没有收到任何其他消息,好像 KeyListener 甚至没有。

When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.

我原以为可能因为焦点不在 JFrame

所以他们 KeyListener 不会收到任何事件。但是,我很确定它是。

I was thinking that it could be because the focus is not on the JFrame
and so they KeyListener doesn't receive any events. But, I'm pretty sure it is.

我有什么遗漏吗?

推荐答案

您必须将keyListener添加到您需要的每个组件。只有具有焦点的组件才会发送这些事件。例如,如果JFrame中只有一个TextBox,则TextBox具有焦点。因此,您还必须将KeyListener添加到此组件。

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

过程相同:

myComponent.addKeyListener(new KeyListener ...);

注意:某些组件无法像JLabel那样集中。

Note: Some components aren't focusable like JLabel.

要将它们设置为可聚焦,您需要:

For setting them to focusable you need to:

myComponent.setFocusable(true);

这篇关于JFrame没有响应的KeyListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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