0

Why doesn't in detect my pressed Key? Nothing happens. The program doesn't tell me when i press w and it doesn't stop when i press escape.

main class:

package awd;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

public class main {

    public static void main(String[] args) {
        do {
            if (Keyboard.isKeyPressed(KeyEvent.VK_W)) System.out.println("W is pressed!");
        } while (!Keyboard.isKeyPressed(KeyEvent.VK_ESCAPE));

    }
}

Keyboard class:

package awd;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

public class Keyboard {

    private static final Map<Integer, Boolean> pressedKeys = new HashMap<>();

    static {
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(event -> {
            synchronized (Keyboard.class) {
                if (event.getID() == KeyEvent.KEY_PRESSED) pressedKeys.put(event.getKeyCode(), true);
                else if (event.getID() == KeyEvent.KEY_RELEASED) pressedKeys.put(event.getKeyCode(), false);
                return false;
            }
        });
    }

    public static boolean isKeyPressed(int keyCode) { // Any key code from the KeyEvent class
        return pressedKeys.getOrDefault(keyCode, false);
    }
}

It should tell me, when w is pressed and it should stop when i press escape.

  • 1
    The bigger question that I have is why would you expect this code to capture keypresses? You're trying to use a Swing GUI KeyboardFocusManager, a class that can help trap keypresses for a Swing GUI program, as a *global* key listener, and this class was never built to work this way. Did you find a webpage or tutorial that told you to use this? If so, can you reference it? – Hovercraft Full Of Eels Dec 03 '22 at 19:32
  • @HovercraftFullOfEels I Found it here by RubyNaxela: https://stackoverflow.com/questions/18037576/how-do-i-check-if-the-user-is-pressing-a-key – Fabi0011 Dec 03 '22 at 19:34
  • 1
    Yes, that code is for AWT or Swing GUI's. If you're looking for a global keyboard listener or key logger, you'll need to use other tools. – Hovercraft Full Of Eels Dec 03 '22 at 19:38

0 Answers0