简体   繁体   English

Java为什么键监听器不起作用?

[英]Java why is the key listener not working?

I do not know why this doesn't work. 我不知道为什么这行不通。 I have already read many posts, and added setFocusable but it just does not work. 我已经阅读了很多帖子,并添加了setFocusable,但是它不起作用。

public class Spiel {  
    public static void main(String[] args) {
        Playground pg = new Playground();
        pg.setLocation(0,0);
        pg.setSize(1000,1000);
        pg.setVisible(true);
        pg.setFocusable(true);
    }
}



import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

public class Playground extends JFrame implements KeyListener {
    Playground(){

    }

    @Override
    public void keyTyped(KeyEvent e) {
        System.exit(0);

    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.exit(0);

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }
}

You only implemented the KeyListener but if you want it to actually work you still need to register it to your frame. 您仅实现了KeyListener但是如果您希望它实际运行,则仍然需要将其注册到框架中。

Playground(){
    addKeyListener(this);  // should do the trick
}

Otherwise your frame wouldn't know that it actually has to listen and call the methods when a key is pressed. 否则,您的框架将不会知道按下键时实际上必须监听并调用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM