开发者

How to add a keylistener to JFrame Subclass

I implemented all of the necessary methods and added the "implements KeyListener" and added the addKeyListener and setFocus(true) but I get no keyresponses. The JFrame includes a c开发者_开发百科anvas class that I created. Here is the constructor for the window class.

    setBounds(0,0, width, height);
    setIgnoreRepaint(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    add(MainCanvas.Instance());
    this.getContentPane().addKeyListener(this);
    pack();
    setVisible(true);

    if (thread == null)
    {
        thread = new Thread(this);
    }

    thread.start();


Only the focus component will get sent the key events; you need to call requestFocus() on your Canvas.


You should add the KeyListener to the the Canvas instead of JFrame. When you add any component to JFrame (e.g. add(MainCanvas.getInstance()), with default layout (BorderLayout), the component occupies the JFrame view and all your key strokes are being sent to the Canvas and not to JFrame. Try adding the KeyListener to MainCanvas instead of JFrame.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜