Why does the Key/Mouse listener detect mouse presses but not key presses? (Java awt window)

142 Views Asked by At

So, my window detects mouse presses but not key presses.

Here some shortened code:

public class Frame {
    public static final int MAX_WIDTH = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    public static final int MAX_HEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();

    private static final JWindow window = new JWindow();
    private static final DrawMain dm = new DrawMain();
    private static final GIH gih = new GIH();

    public static void init() {
        window.setSize(CVar.clientSizeX, CVar.clientSizeY);
        window.setLocationRelativeTo(null);
        window.setAutoRequestFocus(true);
        window.add(dm);
        window.addMouseListener(mh);
        window.addMouseWheelListener(mh);
        window.addMouseMotionListener(mh);
        window.setVisible(true);
    }

    public static void update() {
            window.remove(dm);
            window.removeMouseListener(mh);
            window.removeMouseMotionListener(mh);
            window.removeMouseWheelListener(mh);
            window.setSize(MAX_WIDTH, MAX_HEIGHT);
            window.setLocationRelativeTo(null);
            window.add(dm);
            window.setAutoRequestFocus(true);
            window.setAlwaysOnTop(true);
            window.addMouseListener(gih);
            window.addMouseWheelListener(gih);
            window.addMouseMotionListener(gih);
            window.addKeyListener(gih);
            window.setVisible(true);
    }
}

public class GIH implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener {
    @Override
    public void keyReleased(KeyEvent e) {
        System.out.println(e.getKeyChar());
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        switch (e.getButton()) {
            case MouseEvent.BUTTON1 -> {
                System.out.println("Mouse 1 clicked");
            }
            case MouseEvent.BUTTON3 -> {
                System.out.println("Mouse 3 clicked");
            }
        }
    }

For whatever reason, i get my Mouse 1 clicked message if i click, but neither the key char if i press a key nor the output that the game would usually give on key press. Instead i write the respective character into IntelliJ (my IDE). I tried out multiple variations of window and dm.requestFocus() and window.setAutoRequestFocus(true) but none of them works. Does anyone know why? (Notice: dm is just a class with a paintComponent method)

1

There are 1 best solutions below

3
Gennadii On

try to add window.addKeyListener(...) into init() method.