所以,我的窗口检测到鼠标按下而不是按键。
这里有一些缩短的代码:
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 方法的类)