MemeMan3000
MemeMan3000

Reputation: 11

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.

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

    }
}

Upvotes: 0

Views: 30

Answers (1)

GameDroids
GameDroids

Reputation: 5662

You only implemented the KeyListener but if you want it to actually work you still need to register it to your frame.

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.

Upvotes: 1

Related Questions