Reputation: 38
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?
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
.
What can I do to resolve this issue?
Upvotes: 0
Views: 2108
Reputation: 209004
You haven't initialized 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
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)
See KeyEvent javadoc for more information on values you can pass to the constructor
Also, take a look at Javabeans
Upvotes: 1