So I have a key listener in Java that moves a rectangle on a JFrame either up, down, left, or right for which I am using the W, A, S, and D keys. Usually, and especially in games, pressing 2 keys should yeild diagonal movement. An example would be you press W and D at the same time, and the expected behavior is to move diagonally to the right upwards. However, the key listener only detects one key at a time. I know I can do something where I detect multiple keys at a time and then write new code as if it were a new key but is there a way to execute two pieces of code under two different keys at the same time? If not, how can I test multiple keys at a time?
Here is a minimal reproducible that sets up a rectangle that moves with the W, A, S, and D keys.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JPanel implements KeyListener {
private int x = 200, y = 200;
public static void main(String[] args) {
// TODO Auto-generated method stub
new Test().create();
}
public void paintComponent(Graphics tool) {
super.paintComponent(tool);
tool.drawRect(x, y, 50, 50);
}
public void create() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.add(this);
frame.addKeyListener(this);
frame.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
switch(e.getKeyCode()) {
case KeyEvent.VK_W:
y -= 3;
break;
case KeyEvent.VK_S:
y += 3;
break;
case KeyEvent.VK_A:
x -= 3;
break;
case KeyEvent.VK_D:
x += 3;
break;
}
repaint();
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}