Game Development Reference
In-Depth Information
How it works...
This recipe explains that when a button that represents a key binding is clicked, the corres-
ponding element is selected. By using a pattern in the annotation for the
keyClicked
method, rather than an ID, we can capture all the keys using the wildcard
.*
. This is also
why the naming of the elements is important.
Once an element is selected,
KeyEventListener
will start to listen for a key to be
pressed on the keyboard. We set the text of the button to be the text representation of the
key. In many cases, we can use the
getKeyChar
method of
KeyInputEvent
for this;
however, not all the methods have a character like representation, hence the use of the
Keyboard
class and
getKeyName
method instead. This method tends to output a string
representation instead.
The
changeMapping
method first sees whether there is a current binding for the key
pressed and deletes it if that is the case. This is not enough, however, since we also need to
delete any previous bindings for that input. This is why we also iterate over the current
mappings to see whether any of them match the binding that this key press was for; if yes,
it deletes them too.