Wednesday, 28 August 2013

KeyAdapter not working

KeyAdapter not working

I just wrote some small code trying to get my KeyEvent manager to work.
As you can see i created a JFrame and added the gameComponent which is an
object of the Game class. I set the JPanel focusable and requested the
focus. Then a KeyAdapter called TAdapter was set as KeyAdapter. You can
see the class at the very and of the code it extends a KeyAdapter and the
method keyPressed().
I told the program to print "pressed" to my console when a key is pressed
but nothing happens.
I cannot figure out what I've done wrong, maybe somebody sees some bugs i
don't see by myself?
Any help is appreciated
Thanks in advance
public class Game extends JPanel {
public static final int WIDTH = 320;
public static final int HEIGHT = 240;
public static final int SCALE = 3;
public Game() {
addKeyListener(new TAdapter());
setFocusable(true);
requestFocus();
}
public static void main(String[] args) {
Game gameComponent = new Game();
Dimension size = new Dimension(WIDTH*SCALE, HEIGHT*SCALE);
JFrame frame = new JFrame("Invaders");
frame.setVisible(true);
frame.setSize(size);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(gameComponent);
}
public class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
System.out.println("Pressed");
}
}
}

No comments:

Post a Comment