Cannot make a keylistener work

帅比萌擦擦* 提交于 2019-12-13 00:09:05

问题


I have public class MainFrame extends JFrame implements ActionListener {

and then later on:

public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_LEFT) {
        int x = ball.getX() + 1;
         ball.setX(x);
        }
        }

however it does not seem to respond when I believe it should.

If I add keylistener instead of actionlister I cannot compile which I can't understand. I'm new to java however i'm used to C#


回答1:


  1. You need to implement java.awt.event.KeyListener not a ActionListener to listen for key events.
  2. You need to register your listener on the element (frame) you want to listen on by invoking addKeyListener(...).

Example:

public class TestFrame extends JFrame implements KeyListener {

    public static void main(String[] args) throws FileNotFoundException {
        TestFrame testFrame = new TestFrame();
        testFrame.setSize(100, 100);
        testFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        testFrame.addKeyListener(testFrame);
        testFrame.setVisible(true);
    }

    @Override
    public void keyTyped(KeyEvent e) {    }
    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println(e);
    }
    @Override
    public void keyReleased(KeyEvent e) {   }
}


来源:https://stackoverflow.com/questions/22131146/cannot-make-a-keylistener-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!