I have my code.
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == 37){
personx -=2;
}
if (e.getKeyCode() == 38){
persony -=2;
}
if (e.getKeyCode() == 39){
personx +=2;
}
if (e.getKeyCode() == 40){
persony +=2;
}
try {
Thread.sleep((long) 0.04);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
The code will not move the character.
I checked if it was being called and I wrote:
public void keyPressed(KeyEvent e) {
System.out.println("Test");
}
But it did not print Test.
Your code suggests that you’re working on either a Swing or an AWT GUI. Either way for KeyListeners to work you need to:
If this were a Swing GUI, I’d recommend that you not in fact use a KeyListener but rather use Key Bindings since these are more flexible than KeyListeners and allow you to re-use AbstractActions in multiple parts of your program.