Skip to content

Commit 267bfd3

Browse files
committed
Fix keyPressed for multiple keys
Java2D and FX2D send multiple PRESSED and only one RELEASE event (at least on Windows). Therefore we have to keep track of what is pressed and what not. Most keyboards do not support pressing more than ~10 keys simultaneously, so this should not cause any performance problems. Fixes #5049
1 parent f1b83c3 commit 267bfd3

1 file changed

Lines changed: 9 additions & 5 deletions

File tree

core/src/processing/core/PApplet.java

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -658,7 +658,7 @@ public class PApplet implements PConstants {
658658
* @see PApplet#keyReleased()
659659
*/
660660
public boolean keyPressed;
661-
int keyPressedCount;
661+
List<Long> pressedKeys = new ArrayList<>(6);
662662

663663
/**
664664
* The last KeyEvent object passed into a mouse function.
@@ -2935,13 +2935,14 @@ protected void handleKeyEvent(KeyEvent event) {
29352935

29362936
switch (event.getAction()) {
29372937
case KeyEvent.PRESS:
2938-
keyPressedCount++;
2938+
Long hash = ((long) keyCode << Character.SIZE) | key;
2939+
if (!pressedKeys.contains(hash)) pressedKeys.add(hash);
29392940
keyPressed = true;
29402941
keyPressed(keyEvent);
29412942
break;
29422943
case KeyEvent.RELEASE:
2943-
keyPressedCount--;
2944-
keyPressed = (keyPressedCount > 0);
2944+
pressedKeys.remove(((long) keyCode << Character.SIZE) | key);
2945+
keyPressed = !pressedKeys.isEmpty();
29452946
keyReleased(keyEvent);
29462947
break;
29472948
case KeyEvent.TYPE:
@@ -3123,7 +3124,10 @@ public void keyTyped(KeyEvent event) {
31233124
public void focusGained() { }
31243125

31253126

3126-
public void focusLost() { }
3127+
public void focusLost() {
3128+
// TODO: if user overrides this without calling super it's not gonna work
3129+
pressedKeys.clear();
3130+
}
31273131

31283132

31293133

0 commit comments

Comments
 (0)