Drew Wood
Drew Wood

Reputation: 91

KeyListener Not working/Not being called?

I'm making a small program to test out a KeyListener, making the main class, and only class, implement it. I started by making a class within the class, implementing key listener, and adding the line:

this.addKeyListener(new Handler());

But that didn't work so I made the main class implement key listener, and still the KeyPressed/typed/released are not being called. Ive shortened the class a lot, so here it is:

public class Game_Main extends JPanel implements KeyListener{

JLabel ship = new JLabel();
JLabel bg = new JLabel();

static JFrame frame;

public Game_Main(){
    setPreferredSize(size);

    this.addKeyListener(this);


}

public static void main(String[] args){
    Game_Main g = new Game_Main();
    frame = new JFrame();

    frame.setPreferredSize(size);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(g);
    frame.setVisible(true);

}

    public void keyTyped(KeyEvent e) {
        System.out.println("ds");
    }

}

Upvotes: 0

Views: 156

Answers (1)

Paradox
Paradox

Reputation: 26

Another solution for this problem would be to make an instance in the main method for example:

KeyListener() listener = new Game_Main();

Then you can cut the line:

this.addKeyListener(this);

from the constructor and put it in the main method. After than change the first this to frame and the second this to listener, it will work just fine. You simply register or input the listener to the frame in order to execute the event.

Upvotes: 1

Related Questions