java - 为什么键/鼠标侦听器检测到鼠标按下而不是按键?(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() 方法中。
推荐阅读
- c# - 如何在静态堆栈中进行乘法和除法?
- javascript - 从本地存储加载样式表时防止 FOUC
- ios - 如何加载包含数百个 UIImage 实例的数组而不会因为内存激增而导致应用程序崩溃?
- php - 我在 wamp 中收到关于 PHP 路径的错误
- php - HTTP/1.0 405 Method Not Allowed and false with CURL
- javascript - 使用纯文本而不是提及来定义用户
- batch-processing - 根据 Odoo 中的用户选择批量创建
- linux - 如何将linux命令日志捕获到文件中?
- ios - 使用 Katalon Studio 执行自动化脚本无法找到图标
- excel - 匹配两列中的单元格值,如果匹配,则将另一个值复制到空白单元格