开发者

How to add a keylistener to JFrame Subclass

开发者 https://www.devze.com 2023-02-28 12:12 出处:网络
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开发者_开发百科anv

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

精彩评论

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