Advertisement
TeRackSito

Keyboard detect

Jan 17th, 2024
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. package org.example;
  2.  
  3. import java.awt.*;
  4. import java.awt.event.KeyEvent;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. public class Keyboard {
  8.     private final Map<Integer, Boolean> pressedKeys = new HashMap<>();
  9.  
  10.     {
  11.         KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(event -> {
  12.             synchronized (Keyboard.class) {
  13.                 System.out.printf("%s, %s", event.getID(), event.getKeyCode());
  14.                 if (event.getID() == KeyEvent.KEY_PRESSED) pressedKeys.put(event.getKeyCode(), true);
  15.                 else if (event.getID() == KeyEvent.KEY_RELEASED) pressedKeys.put(event.getKeyCode(), false);
  16.                 return false;
  17.             }
  18.         });
  19.     }
  20.  
  21.     public boolean isKeyPressed(int keyCode) { // Any key code from the KeyEvent class
  22.         System.out.println(pressedKeys);
  23.         return pressedKeys.get(keyCode) != null && pressedKeys.get(keyCode);
  24.     }
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement