Best way for typing text with keyboard?

There are any good way to read what keys have been pressed so far to display that on screen like a simple chat program?

That’s possible to do in swing or awt, but I am looking for a way to do this in jME without swing or awt. It seems that inputmanger could be used in some way for this, because the events looks similar to those used in awt or swing.

The best way is probably RawInputListener

1 Like

How does that work? I can’t find any info at all about it.

You register a RawInputListener:

http://hub.jmonkeyengine.org/javadoc/com/jme3/input/RawInputListener.html



With the InputManager:

http://hub.jmonkeyengine.org/javadoc/com/jme3/input/InputManager.html#addRawInputListener(com.jme3.input.RawInputListener)



And it gets notified about events before any of the normal event handlers. If you consume the KeyInputEvents…

http://hub.jmonkeyengine.org/javadoc/com/jme3/input/event/InputEvent.html#setConsumed()



…then they don’t even get delivered to any other handlers.



Though if you don’t need to worry about consuming the events then you can just watch for all of the “pressed” key events and add their key char (http://hub.jmonkeyengine.org/javadoc/com/jme3/input/event/KeyInputEvent.html#getKeyChar()) to your string. You’ll even get repeats when the user holds the key down, etc…



It’s probably worth filtering to just add characters that are actually displayable.

1 Like

Hmm, I don’t really understand… Should I do an own class with RawInputClass as base class?

The listener idiom is so fundamental to Java development that I just assume that all Java developers must have encountered it before.



RawInputListener is an interface. You must write your own class that implements it. Then create a new instance of this class (using ‘new’) and pass that to InputManager. You could also use an anonymous inner class but that may be pushing the boundaries of understanding a little far at this point.



Basically:



[java]

public class MyListenerClass implements RawInputListener {

String theString = “”;



…implementations of all of the methods go here but most of them are empty because you

…are only interested in…

public void onKeyEvent( KeyInputEvent evt ) {

if( evt.isPressed() ) {

theString += evt.getKeyChar();

}

}

}[/java]



Then somewhere else, maybe in simpleInit():

[java]

MyListener l = new MyListener();

inputManager.addRawInputListener( l );

[/java]



…filtering the key char to be only displayable characters is left as an exercise for the reader.

1 Like

…alternately, you could just use a nifty gui.

Thank you, I was about to figure that out aswell :stuck_out_tongue: