JFrame 的无响应 KeyListener [英] Unresponsive KeyListener for JFrame

查看:25
本文介绍了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天全站免登陆