From cb229d3f922344af0fd4166cbf72ff7243c5d262 Mon Sep 17 00:00:00 2001 From: Jakub Valtar Date: Fri, 5 May 2017 01:16:50 +0200 Subject: [PATCH] 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 --- core/src/processing/core/PApplet.java | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java index 6c36d0265..41dbfaacd 100644 --- a/core/src/processing/core/PApplet.java +++ b/core/src/processing/core/PApplet.java @@ -658,7 +658,7 @@ public class PApplet implements PConstants { * @see PApplet#keyReleased() */ public boolean keyPressed; - int keyPressedCount; + List pressedKeys = new ArrayList<>(6); /** * The last KeyEvent object passed into a mouse function. @@ -2935,13 +2935,14 @@ public class PApplet implements PConstants { switch (event.getAction()) { case KeyEvent.PRESS: - keyPressedCount++; + Long hash = ((long) keyCode << Character.SIZE) | key; + if (!pressedKeys.contains(hash)) pressedKeys.add(hash); keyPressed = true; keyPressed(keyEvent); break; case KeyEvent.RELEASE: - keyPressedCount--; - keyPressed = (keyPressedCount > 0); + pressedKeys.remove(((long) keyCode << Character.SIZE) | key); + keyPressed = !pressedKeys.isEmpty(); keyReleased(keyEvent); break; case KeyEvent.TYPE: @@ -3123,7 +3124,10 @@ public class PApplet implements PConstants { public void focusGained() { } - public void focusLost() { } + public void focusLost() { + // TODO: if user overrides this without calling super it's not gonna work + pressedKeys.clear(); + }