gpt4 book ai didi

java - KeyListener - 调用了 keyPressed 但未调用 KeyReleased

转载 作者:行者123 更新时间:2023-11-30 07:20:25 24 4
gpt4 key购买 nike

无需发布太多代码,简而言之,我有一个表现有趣的 KeyListener

我有一个 JPanel,我这样实现我的 KeyListener:

keyboard = new KeyBoard(); // implements KeyListener
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new DefaultKeyEventDispatcher(keyboard));

我之前也试过这样的:

theJPanel.addKeyListener(myKeyListener);
theJPanel.setFocusable(true);
theJPanel.requestFocusInWindow();

主要问题:

当问题发生时,public void keyPressed(KeyEvent e) 总是被调用,但是public void keyReleased(KeyEvent e) 从不被调用。

当它发生时似乎无法预测,因为其他时候一切正常。如果我等待大约 5 分钟并重新运行程序,这个错误就会消失 :/

编辑:(忘记发布 DefaultKeyEventDispatcher 代码)

package game.keyboard;

import java.awt.KeyEventDispatcher;
import java.awt.event.KeyEvent;

public class DefaultKeyEventDispatcher implements KeyEventDispatcher {

private KeyBoard keyboard;

public DefaultKeyEventDispatcher(KeyBoard keyboard) {
this.keyboard = keyboard;
}

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
keyboard.keyPressed(e);
} else if (e.getID() == KeyEvent.KEY_RELEASED) {
keyboard.keyReleased(e);
} else if (e.getID() == KeyEvent.KEY_TYPED) {
keyboard.keyTyped(e);
}
return false;
}
}

编辑 2. KeyBoard 类中的示例

package game.keyboard;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyBoard implements KeyListener {

private boolean[] keys;

private long[] keyPressedTime;

public KeyBoard() {
keys = new boolean[KeyEvent.KEY_LAST];
keyPressedTime = new long[KeyEvent.KEY_LAST];
}

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
keys[e.getKeyCode()] = true;
keyPressedTime[e.getKeyCode()] = System.currentTimeMillis();
}

@Override
public void keyReleased(KeyEvent e) {
keys[e.getKeyCode()] = false;
keyPressedTime[e.getKeyCode()] = -1;
}

public long keyPressedTime(int k) {
return keyPressedTime[k];
}

public boolean isKeyPressed(int k) {
return keys[k];
}

public boolean isKeyCombo(int[] k) {
boolean ret = true;
for(int i = 0;i < k.length; i++) {
ret &= keys[k[i]];
}
return ret;
}

}

最佳答案

这...

keyboard = new KeyBoard(); // implements KeyListener
KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new DefaultKeyEventDispatcher(keyboard));

不是注册KeyListener的方法。这将允许您查看应用程序处理的所有 key 。 KeyEventDispatcher 没有 keyPressedkeyReleased 方法,只有 dispatchKeyEvent

JDK 中没有 DefaultKeyEventDispatcher 这样的类,所以你必须使用自定义版本,这意味着,我们不知道问题到底是什么,因为我们无法复制它或研究一下。

如果不知道您要达到的目标是什么,就不可能提供准确的指导,但您可能希望从 How to Write a Key Listener 开始

关于java - KeyListener - 调用了 keyPressed 但未调用 KeyReleased,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14037631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com