Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the user is pressing a key?

Tags:

java

key

input

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!

like image 808
Saucymeatman Avatar asked Aug 03 '13 21:08

Saucymeatman


People also ask

How can you tell if someone pressed a key?

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.

How do I check if a key is pressed in HTML?

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.

How do you check if a key is being pressed in Java?

Use KeyEvent. getKeyChar() and KeyEvent. getKeyCode() to find out which key the user pressed.

Which syntax can be used to check if the key is still pressed or not?

The keyIsDown() function checks if the key is currently down, i.e. pressed.


1 Answers

In java you don't check if a key is pressed, instead you listen to KeyEvents. 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.

like image 186
Elist Avatar answered Oct 21 '22 15:10

Elist