gpt4 book ai didi

java - 如何在Java中创建一个空的KeyEvent和SetKeyCode(keyCode)?

转载 作者:行者123 更新时间:2023-12-01 13:44:47 26 4
gpt4 key购买 nike

在我的项目中,我尝试从发送 writeInt(e.getKeyCode()) 的另一台计算机接收 dataInputStream,即 readInt() 到这台计算机,但是当我收到 keyCode 时,如何将其放入 KeyEvent 对象中?

这是我的编码的一部分:

KeyEvent enemyKey;
try{
key = inputFromClient.readInt();
if(key!=0) {
enemyKey.setKeyCode(key);
player2.keyPressed(enemyKey);
}
}catch(Exception ex){
System.out.println(ex);
}

通过执行上面的代码,我得到 NullPointerException,因为 KeyEvent heavenlyKey 为 null。我该如何解决这个问题?

最佳答案

您还没有初始化KeyEventenemyKey;您可以使用此构造函数初始化它

public KeyEvent(Component source,
int id,
long when,
int modifiers,
int keyCode,
char keyChar)

source - The Component that originated the event

id - An integer indicating the type of event. For information on allowable values, see the class description for KeyEvent

when - A long integer that specifies the time the event occurred. Passing negative or zero value is not recommended

modifiers - The modifier keys down during event (shift, ctrl, alt, meta). Passing negative value is not recommended. Zero value means that no modifiers were passed. Use either an extended _DOWN_MASK or old _MASK modifiers, however do not mix models in the one event. The extended modifiers are preferred for using

keyCode - The integer code for an actual key, or VK_UNDEFINED (for a key-typed event)

keyChar - The Unicode character generated by this event, or CHAR_UNDEFINED (for key-pressed and key-released events which do not map to a valid Unicode character)

参见KeyEvent javadoc有关可以传递给构造函数的值的更多信息

此外,请查看 Javabeans

关于java - 如何在Java中创建一个空的KeyEvent和SetKeyCode(keyCode)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20439207/

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