Reputation: 752
I'm working on a java project and i'm having a hard time to make the Keyboard input handler work. I have two separate classes, one called KeyInput and one called Player. When i'm starting the Player class and I press a key nothing will be printed, but if i use println in the KeyInput class it will work. So it does register when you press a button only it won't work when I want to make use of it within the Player class.
Player class:
public class Player extends JFrame {
private static final int IMAGE_TYPE = BufferedImage.TYPE_INT_ARGB;
private BufferedImage img;
KeyInput input
public Player() {
super();
this.add(new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
});
img = new BufferedImage(660, 500, IMAGE_TYPE );
this.setSize(img.getWidth(), img.getHeight());
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
input = new KeyInput(this);
if(input.up.isPressed()){
System.out.println("Up");
}
this.setVisible( true );
}
}
KeyInput class:
public class KeyInput implements KeyListener {
BufferedImage img = null;
public KeyInput(Player player) {
player.requestFocus(); // click window to move bug fix he didn't add this
player.addKeyListener(this);
}
public class Key {
private int numTimesPressed = 0;
private boolean pressed = false;
public int getNumTimesPressed() {
return numTimesPressed;
}
public boolean isPressed() {
return pressed;
}
public void toggle(boolean isPressed) {
pressed = isPressed;
if (isPressed) {
numTimesPressed++;
}
}
}
public List<Key> keys = new ArrayList<Key>();
public Key up = new Key();
public Key down = new Key();
public Key left = new Key();
public Key right = new Key();
public Key esc = 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 || KeyCode == KeyEvent.VK_UP
|| KeyCode == KeyEvent.VK_NUMPAD8) {
up.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_S || KeyCode == KeyEvent.VK_DOWN
|| KeyCode == KeyEvent.VK_NUMPAD2) {
down.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_A || KeyCode == KeyEvent.VK_LEFT
|| KeyCode == KeyEvent.VK_NUMPAD4) {
left.toggle(isPressed);
}
if (KeyCode == KeyEvent.VK_D || KeyCode == KeyEvent.VK_RIGHT
|| KeyCode == KeyEvent.VK_NUMPAD6) {
right.toggle(isPressed);
}
if(KeyCode == KeyEvent.VK_ESCAPE){
System.exit(0);
}
}
}
Upvotes: 0
Views: 171
Reputation: 2490
You should use Key Bindings to assign key stroke to action on specific component.
A qoute from docs
component.getInputMap().put(KeyStroke.getKeyStroke("F2"),
"doSomething");
component.getActionMap().put("doSomething",
anAction);
//where anAction is a javax.swing.Action
https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html#howto
Upvotes: 2