[英]How to create an empty KeyEvent and SetKeyCode(keyCode) in Java?
In my project, I'm trying to receive a dataInputStream
which is readInt()
from another computer that sends writeInt(e.getKeyCode())
to this computer, but when I receives the keyCode
, how do I put it into a KeyEvent
object? 在我的项目中,我试图从另一台计算机接收到
readInt()
的dataInputStream
,该数据发送writeInt(e.getKeyCode())
到这台计算机,但是当我收到keyCode
,如何将其放入KeyEvent
对象中?
Here's a part of my coding: 这是我的编码的一部分:
KeyEvent enemyKey;
try{
key = inputFromClient.readInt();
if(key!=0) {
enemyKey.setKeyCode(key);
player2.keyPressed(enemyKey);
}
}catch(Exception ex){
System.out.println(ex);
}
By executing the code above, I get NullPointerException because KeyEvent
enemyKey is null
. 通过执行上面的代码,我得到NullPointerException,因为
KeyEvent
敌人键为null
。 What can I do to resolve this issue? 我该怎么做才能解决这个问题?
You haven't initialized KeyEvent enemyKey;
您尚未初始化
KeyEvent enemyKey;
You can initialize it with this constructor 您可以使用此构造函数对其进行初始化
public KeyEvent(Component source,
int id,
long when,
int modifiers,
int keyCode,
char keyChar)
source - The Component that originated the event
source -发起事件的组件
id - An integer indicating the type of event.
id-一个整数,指示事件的类型。 For information on allowable values, see the class description for KeyEvent
有关允许值的信息,请参见KeyEvent的类描述。
when - A long integer that specifies the time the event occurred.
when-一个长整数,指定事件发生的时间。 Passing negative or zero value is not recommended
不建议传递负值或零值
modifiers - The modifier keys down during event (shift, ctrl, alt, meta).
修饰符 -修饰符在事件(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.
使用扩展的_DOWN_MASK或旧的_MASK修饰符,但是不要在一个事件中混合使用模型。 The extended modifiers are preferred for using
首选使用扩展修饰符
keyCode - The integer code for an actual key, or VK_UNDEFINED (for a key-typed event)
键代码 -对于实际密钥的整数代码,或VK_UNDEFINED(为一个键类型的事件)
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)
keyChar-此事件或CHAR_UNDEFINED生成的Unicode字符(用于未映射到有效Unicode字符的键按下和键释放的事件)
See KeyEvent javadoc for more information on values you can pass to the constructor 有关可以传递给构造函数的值的更多信息,请参见KeyEvent javadoc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.