JPanel 不响应 KeyListener 事件 [英] JPanel doesn't response to KeyListener event

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

问题描述

我有一个 JFrame 的子类,它使用从 JPanel

I have a subclass of JFrame that uses a class extended from JPanel

public class HelloWorld extends JPanel implements KeyListener

我将 HelloWorld 的对象添加到框架 - app.add(helloWorld);.现在,当我按下任何键盘键时,KeyListener 方法的非被调用并且 helloWorld 似乎没有窗口焦点.我也试过调用 helloWorld.requestFocusInWindow(); 但仍然没有响应.

I add an object of HelloWorld to the frame - app.add(helloWorld);. Now, when I press any keyboard key non of the KeyListener methods gets called and it seems that helloWorld doesn't have window focus. I have tried also to invoke helloWorld.requestFocusInWindow(); but still doesn't respond.

如何让它响应按键?

推荐答案

您是否为 HelloWorld 面板设置了 KeyListener 面板本身?此外,您可能需要将该面板设置为可聚焦.我通过这段代码对其进行了测试,它似乎可以正常工作

Did you set that KeyListener for your HelloWorld panel would be that panel itself? Also you probably need to set that panel focusable. I tested it by this code and it seems to work as it should

class HelloWorld extends JPanel implements KeyListener{
    public void keyTyped(KeyEvent e) {
        System.out.println("keyTyped: "+e);
    }
    public void keyPressed(KeyEvent e) {
        System.out.println("keyPressed: "+e);
    }
    public void keyReleased(KeyEvent e) {
        System.out.println("keyReleased: "+e);
    }
}

class MyFrame extends JFrame {
    public MyFrame() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(200,200);

        HelloWorld helloWorld=new HelloWorld();

        helloWorld.addKeyListener(helloWorld);
        helloWorld.setFocusable(true);

        add(helloWorld);
        setVisible(true);
    }
    public static void main(String[] args) {
        new MyFrame();
    }
}

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

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