In java I have a program that needs to check continuously if a user is pressing a key. So In psuedocode, somthing like
if (isPressing("w")) { //do somthing }
Thanks in advance!
To detect keypress, we will use the is_pressed() function defined in the keyboard module. The is_pressed() takes a character as input and returns True if the key with the same character is pressed on the keyboard.
In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.
Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.
The keyIsDown() function checks if the key is currently down, i.e. pressed.
In java you don't check if a key is pressed, instead you listen to KeyEvent
s. The right way to achieve your goal is to register a KeyEventDispatcher
, and implement it to maintain the state of the desired key:
import java.awt.KeyEventDispatcher; import java.awt.KeyboardFocusManager; import java.awt.event.KeyEvent; public class IsKeyPressed { private static volatile boolean wPressed = false; 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; } break; case KeyEvent.KEY_RELEASED: if (ke.getKeyCode() == KeyEvent.VK_W) { wPressed = false; } break; } return false; } } }); } }
Then you can always use:
if (IsKeyPressed.isWPressed()) { // do your thing. }
You can, of course, use same method to implement isPressing("<some key>")
with a map of keys and their state wrapped inside IsKeyPressed
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With