I want a program that will read what keys are pressed in one file using KeyEvent, and write it to console in the next. I have the keys Q & W set up, but whenever I try to run the program, it spams "Key Q Pressed" and "Key W Pressed"
I've tried changing KeyPressed to KeyTyped, nothing. Seperate functions for KeyPressed, KeyTyped, and KeyReleased, nothing. Removing CHAR_UNDEFINED, nothing.
Main IsKeyPressed.java
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
public class IsKeyPressed {
private static volatile boolean qPressed = false;
private static volatile boolean wPressed = false;
public static boolean isQPressed() {
synchronized (IsKeyPressed.class) {
return qPressed;
}
}
public static boolean isWPressed() {
synchronized (IsKeyPressed.class) {
return wPressed;
}
}
public static void main(String[] args) {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
@Override
public boolean dispatchKeyEvent(KeyEvent ke) {
synchronized (IsKeyPressed.class) {
switch(ke.getID()) {
case KeyEvent.KEY_PRESSED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = true;
} else if (ke.getKeyCode() == KeyEvent.VK_Q) {
qPressed = true;
}
break;
case KeyEvent.KEY_RELEASED:
if (ke.getKeyCode() == KeyEvent.VK_W) {
wPressed = false;
} else if (ke.getKeyCode() == KeyEvent.VK_Q) {
qPressed = false;
}
break;
}
return false;
}
}
});
}
public void keyTyped(KeyEvent ke) {
//test
}
public void keyPressed(KeyEvent ke) {
//test
}
public void keyReleased(KeyEvent ke) {
//test
}
}
Public class in Test.java
static boolean randomVariableName = true;
public static void main(String[] args) {
while (randomVariableName == true) {
if (IsKeyPressed.isWPressed()); {
System.out.println("keydown.W");
}
if (IsKeyPressed.isQPressed()); {
System.out.println("keydown.Q");
}
}
}
I expect hitting Q on my keyboard will make the console print keydown.Q, but instead it just spams keydown.Q and keydown.W