Skip to content

Keyboard methods to simplify adding event listeners #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import java.util.List;
import java.util.Iterator;

import static org.academiadecodigo.simplegraphics.keyboard.KeyboardEventType.KEY_PRESSED;
import static org.academiadecodigo.simplegraphics.keyboard.KeyboardEventType.KEY_RELEASED;

/**
* Instantiate a Keyboard for obtaining key handling capability
*/
Expand Down Expand Up @@ -35,6 +38,33 @@ public void addEventListener(KeyboardEvent keyboardEvent) {
keyboardEventArrayList.add(keyboardEvent);
}

/**
* Add a new Keyboard event listener
* @see KeyboardEvent
* @param key the associated key code
* @see KeyboardEventType
* @param type the event to add
*/
public void addEventListener(int key, KeyboardEventType type) {
KeyboardEvent e = new KeyboardEvent();
e.setKey(key);
e.setKeyboardEventType(type);
addEventListener(e);
}

/**
* Add Keyboard event listeners to a group of keys
* @see KeyboardEvent
* @param keys the key codes
* @see KeyboardEventType
* @param type the event to add
*/
public void addEventListeners(int[] keys, KeyboardEventType type) {
for (int key : keys) {
addEventListener(key, type);
}
}

/**
* Remove an existing Keyboard event listener
* @param keyboardEvent the event to remove
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ public void test() throws InterruptedException {
event.setKeyboardEventType(KeyboardEventType.KEY_PRESSED);
k.addEventListener(event);

k.addEventListener(KeyboardEvent.KEY_ENTER, KeyboardEventType.KEY_PRESSED);
k.addEventListeners(new int[]{KeyboardEvent.KEY_ESC, KeyboardEvent.KEY_Q}, KeyboardEventType.KEY_PRESSED);

Mouse m = new Mouse(this);

Rectangle rect = new Rectangle(10, 10, 400, 400);
Expand Down Expand Up @@ -75,7 +78,20 @@ public void test() throws InterruptedException {

@Override
public void keyPressed(KeyboardEvent e) {
System.out.println("SPACE KEY PRESSED");
switch (e.getKey()){
case KeyboardEvent.KEY_SPACE:
System.out.println("SPACE KEY PRESSED");
break;
case KeyboardEvent.KEY_ENTER:
System.out.println("ENTER WAS PRESSED");
break;
case KeyboardEvent.KEY_ESC:
System.out.println("ESC WAS PRESSED");
break;
case KeyboardEvent.KEY_Q:
System.out.println("Q WAS PRESSED");
break;
}

}

Expand Down