为什么键/鼠标侦听器检测到鼠标按下而不检测到按键按下? Java awt窗口

问题描述

因此,我的窗口检测到鼠标按下但检测不到按键。

下面是一些缩短的代码:

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");
            }
        }
    }

无论出于什么原因,如果我单击,都会收到“鼠标1单击”消息,但是如果我按下某个键,则不会显示键字符,也不会显示游戏通常会在按下该键时显示的输出。相反,我将相应的字符写入IntelliJ(我的IDE)。我尝试了window和dm.requestFocus()和window.setAutoRequestFocus(true)的多种变体,但它们都不起作用。有人知道为什么吗? (注意:dm只是一个带有paintComponent方法的类)

解决方法

尝试将window.addKeyListener(...)添加到init()方法中。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...