mac-comp127 / kilt-graphics

Graphics and UI library for learning software development principles in Java
https://mac-comp127.github.io/kilt-graphics/
2 stars 17 forks source link

Key event handling #7

Closed pcantrell closed 4 years ago

pcantrell commented 4 years ago

This pull request adds three different ways of handling key events:

If you want to take some action at the moment a key is pressed or released, use onKeyDown() and onKeyUp():

canvas.onKeyDown(event -> {
  if (event.getKey() == Key.UP_ARROW) {
    player.jump();  // jump when the key goes down
  }
});

If you want to take some action as long as a key is held down, use [getKeysPressed()](https://mac-comp127-f19.github.io/127-shared/comp127graphics/CanvasWindow.html#getKeysPressed()) inside an animate() lambda:

canvas.animate(() -> {
  if (canvas.getKeysPressed().contains(Key.LEFT_ARROW)) {
    player.moveLeft();  // keep moving left as long as player holds key down
  }
});

These previous two methods track keys on the keyboard. If you want to know what character the user typed, taking into account keyboard layout, modifiers keys, etc., then use onCharacterTyped():

private String lettersTyped = "";
...
canvas.onCharacterTyped(c -> lettersTyped += c);

Please follow the links above to read more details in the Javadoc for these methods.

Fixes #1.