[英]Why does the Key/Mouse listener detect mouse presses but not key presses? (Java awt window)
So, my window detects mouse presses but not key presses.所以,我的 window 检测到鼠标按下而不是按键。
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.无论出于何种原因,如果我点击,我会收到鼠标 1 的点击消息,但如果我按下一个键,我既不会收到键字符,也不会收到游戏通常会在按键时给出的 output。 Instead i write the respective character into IntelliJ (my IDE).
相反,我将相应的字符写入 IntelliJ(我的 IDE)。 I tried out multiple variations of window and dm.requestFocus() and window.setAutoRequestFocus(true) but none of them works.
我尝试了 window 和 dm.requestFocus() 和 window.setAutoRequestFocus(true) 的多种变体,但它们都不起作用。 Does anyone know why?
有谁知道为什么? (Notice: dm is just a class with a paintComponent method)
(注意:dm 只是一个带有paintComponent 方法的class)
try to add window.addKeyListener(...) into init() method.尝试将 window.addKeyListener(...) 添加到 init() 方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.