user3183586
user3183586

Reputation: 167

KeyListener Methods Not Being Called

I made a extremely simple program to understand the workings of KeyListener, but for some reason none of my methods are being called when any key is hit. I would really appreciate if someone could give me some input.

import java.applet.*;
import java.awt.event.*;


public class ClassOne extends Applet implements KeyListener {


    public void init(){
        this.addKeyListener(this);
    }


    @Override
    public void keyPressed(KeyEvent arg0) {
        System.out.println("Pressed");

    }

    @Override
    public void keyReleased(KeyEvent k) {
        System.out.println("Released");
    }

    @Override
    public void keyTyped(KeyEvent arg0) {
        // TODO Auto-generated method stub

    }

}

Upvotes: 1

Views: 134

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347194

KeyListeners are designed to provide key notifications to the component that they registered to only when the component is focusable AND has focus. That means that it won't respond to key events if some other component has focus (or your component isn't focusable).

A better solution would be to use the Key Bindings API, but this would require you to use a JApplet, which the raises the question of, why are you using an Applet anyway...?

Upvotes: 1

user3183586
user3183586

Reputation: 167

I needed to set the following in init():

setFocusable(true);

Upvotes: 0

Related Questions