I'm programming a game, but the keyListener doesn't work. Here is the source code:
import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class InputHandler implements KeyListener{ public InputHandler(Game game) { game.addKeyListener(this); } public class Key { private boolean pressed = false; public boolean isPressed() { return pressed; } public void toggle(boolean isPressed) { pressed = isPressed; } } public Key up = new Key(); public Key down = new Key(); public Key left = new Key(); public Key right = new Key(); public void keyPressed(KeyEvent e) { toggleKey(e.getKeyCode(),true); } public void keyReleased(KeyEvent e) { toggleKey(e.getKeyCode(),false); } public void keyTyped(KeyEvent e) { } public void toggleKey(int keyCode, boolean isPressed) { if(keyCode == KeyEvent.VK_W){ up.toggle(isPressed); } if(keyCode == KeyEvent.VK_S){ down.toggle(isPressed); } if(keyCode == KeyEvent.VK_A){ left.toggle(isPressed); } if(keyCode == KeyEvent.VK_D){ right.toggle(isPressed); } } }
and in class Game:
...
...public InputHandler input = new InputHandler(this);
//in a method, that gets called every gametick:
if(input.up.isPressed()==true){ System.out.println("up"); //This doesn't work! }
My Question is: Why will it not say "up", if I press "w" ? Thanks in advance for every aswer