Recognizing multiple key presses in As3

Hi,
I have a simple game with three keyboard inputs - left, right and fire
I want to be able to log when a key is pressed and released. In the game, you can be in the following states:
None
Left only - keyz on the keyboard
Right only - keyc on the keyboard
Fire only - keyx on the keyboard
Left and Fire - keyz and Keyx on the keyboard
Right and Fire - Keyc and Keyx on the keyboard
When Left key is pressed for example, it should log LeftKeypressStart and when it is released, it shoul log leftKeyPressStop. The same should happen to Right and Fire keys when they are pressed individually.
Now, for the game to be in  Left and Fire state either of the three conditions are true:
Left key can be pressed and held down before the fire button is pressed and held down or
Fire button is pressed and held down before left is pressed and held down or
Both keys pressed down simultenuosly (although this condition will rarely occur as we are not robots)
Similar conditions should be true for the game to be in the Right and Fire State
Now considering the first condition,when Left key is down, I want the game to log LeftKeypressStart but as soon as the Fire key is down, it should log LeftKeyPressStop and also Log LeftandFireKeypressStart. Then if Fire is released first, I want it to log LeftandFirKeypressStop and then log LeftKeyStart. but if Left is released first, it should log  LeftandFirKeypressStop and then lof FireKeyPressStart.
This is what I have at the minute:
private function onKeyPress (evt:KeyboardEvent)
if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
//log Right  
else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
//log Left
else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
//log Fire
else if (evt.keyCode == 67 && evt.keyCode !=90 && evt.keyCode == 88 )
//log RF
private function onKeyRelease(evt:KeyboardEvent)
if (evt.keyCode == 67 && evt.keyCode !=88 && evt.keyCode != 90)
//stop right
else if (evt.keyCode != 67 && evt.keyCode !=88 && evt.keyCode == 90 )
//stop Left
else if (evt.keyCode != 67 && evt.keyCode !=90 && evt.keyCode == 88)
//stop Fire
else if (evt.keyCode == 67 && evt.keyCode == 88  && evt.keyCode !=90 )
// stop RF    

There can only be one evt.keyCode per keypress, so your approach will not work.  All you need to do is determine which key caused the function to execute.  If you want to keep track of which keys are down, just create three Boolean variables, as in...
var leftDown:Boolean = false;
var rightDown:Boolean = false;
var fireDown:Boolean = false;
and set those values to true or false and make use of them in whatever other code you intend.
private function onKeyPress (evt:KeyboardEvent)
if (evt.keyCode == 67)
             rightDown = true  
else if (evt.keyCode ==88)
             leftDown = true
else if (evt.keyCode == 88)
             fireDown = true
// process per whatever values are true/false
and in the key up function set them back to false in a similar fashion.

Similar Messages

  • Multiple Key Pressing

    When I hold Tab + w space doesn't work click (I have my controls set as this for a game).
    Is there anyway to make it so i can hold those two keys and have spacebar work?
    Im on a MacBook Pro Retina 13 inch with latest version of yosemite
    Thanks for the help

    Here is an example of both multiple key press and repeat delay ignore. It is a terrible example of animation. Do not us this animation loop in a game. It will flicker far too much.import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame implements Runnable {
      boolean upPressed=false, downPressed=false, leftPressed=false, rightPressed=false;
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addKeyListener(new KeyAdapter() {
          public void keyPressed(KeyEvent ke) {
         switch (ke.getKeyCode()) {
           case KeyEvent.VK_UP: upPressed = true; break;
           case KeyEvent.VK_DOWN: downPressed = true; break;
           case KeyEvent.VK_LEFT: leftPressed = true; break;
           case KeyEvent.VK_RIGHT: rightPressed = true; break;
          public void keyReleased(KeyEvent ke) {
         switch (ke.getKeyCode()) {
           case KeyEvent.VK_UP: upPressed = false; break;
           case KeyEvent.VK_DOWN: downPressed = false; break;
           case KeyEvent.VK_LEFT: leftPressed = false; break;
           case KeyEvent.VK_RIGHT: rightPressed = false; break;
        setSize(250,250);
        setVisible(true);
        Thread timer = new Thread(this);
        timer.start();
      public static void main(String[] args) {
        new Test();
      public void run() {
        while (true) {
          repaint();
          try { Thread.sleep(30);} catch (Exception e) {}
      public void paint(Graphics g) {
        g.setColor(Color.white);
        g.fillRect(0,0,getWidth(), getHeight());
        g.setColor(Color.black);
        g.drawString("Up",40,40);
        if (upPressed) g.drawString("Pressed",100,40);
        g.drawString("Down",40,60);
        if (downPressed) g.drawString("Pressed",100,60);
        g.drawString("Left",40,80);
        if (leftPressed) g.drawString("Pressed",100,80);
        g.drawString("Right",40,100);
        if (rightPressed) g.drawString("Pressed",100,100);
    }

  • Multiple key press's with Bluetooth Keyboard

    I'm ready to update my mac to a new G5 imac and fancy getting the wireless bluetooth keyboard and mouse with it.
    I have one question, has anyone experienced problems when holding down multiple keys on the keyboard and moving the mouse all at once (Using illustrator)?
    In my office I have the misfortune of having to use a PC, I have had a number of wireless keyboard and mouse combos, all of them when using Illustrator and photoshop can not handle multiple key press's and mouse movement.
    ie if I'm duplicating an object by dragging a copy of it across the screen, on the PC it will work but it always "releases" after a couple of seconds and drops the copy in the where I don't want it which gets very frustrating (this only happens with wireless).
    As I do a lot of work at home, I hoping this wont be the case with the mac's bluetooth K & M.
    thanks
    Russell

    The shift key works just fine on my Bluetooth keyboard.  So I would imagine this is an issue with your keyboard.

  • Multiple key press

    Hai all
    How can a j2me application withstand multiple key press while doing some process.
    Please help me with some ideas
    Thanks
    Jinesh

    Problem is, Redtruck, I can only get FCP to register one press of t. I can reasign select all tracks forward to a single t but when i go to select track forward and press t it asks me if i want to reassign t to this command and then overrides the select all forward shortcut (which reverts back to tttt automatically).
    I can't seem to find a way to enter multiple "t"s when assigning a shortcut.
    I hope this makes sense (I'm almost confusing myself).

  • How do you register multiple key presses at the same time?

    Hi. I'm trying to write a first person game in OpenGL and I'm having some trouble with key listening. Right now I just use the basic AWT KeyListener. The problem that arises is that whenever I hold down a key, such as a movement key, there is a short pause after it moves me in the appropriate direction, and only after the pause does it start continuously moving me. In addition to that, I can't press multiple keys at once to get diagonal movement (I use WASD for movement). Is there something I can do with AWT to fix both of these problems, or is there something other than AWT that I should use that would be better?

    the pause is the typomatic rate of the keyboard, you can avoid that by using the keyPressed and setting a flag then a sleep(myDelayTime).... if they keyRelease--and clearing of the flag--hasn't happened after the sleep, then you're key is still down so keep firing, moving, or what ever.

  • Detecting multiple key presses

    Using the code below I am trying to detect keypresses for a java applet which involves holding down of several keys at once. I have 2 problems, probably related. Firstly I can only detect 3-4 simultaneous keys being held down and secondly the keyPressed and released! events are continually fired while a key is held down not just when it was first pressed as you would think. I would like to be able to detect up to a maximum of 16 keys being held down at once, is this possible? I am working on a unix system in x-windows which I think accounts for the auto-repeat problem, but why am I having trouble detecting multiple simultaneous keys being held down?
    It there a boolean function I can call to check the state of given keys at a given time, that would be very useful?
    Any help is appreciated.
    Ian
    public void keyPressed(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=true;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=true;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
         qdown=true;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=true;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=true;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=true;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=true;
    break;
    }//method keypressed
    public void keyTyped(KeyEvent e) {
    }//method keytyped
    public void keyReleased(KeyEvent e) {
    int keyCode = e.getKeyCode();
    switch(keyCode){
    case java.awt.event.KeyEvent.VK_O: //o
         odown=false;
    break;
    case java.awt.event.KeyEvent.VK_P: //p
         pdown=false;
    break;
    case java.awt.event.KeyEvent.VK_Q: //q
    qdown=false;
    break;
    case java.awt.event.KeyEvent.VK_W: //w
         up=false;
    break;
    case java.awt.event.KeyEvent.VK_A: //a
         left=false;
    break;
    case java.awt.event.KeyEvent.VK_S: //s
         down=false;
    break;
    case java.awt.event.KeyEvent.VK_D: //d
         right=false;
    break;
    }//method keyReleased

    Did you ever find a solution to this problem. I am experiencing a similar problem. I want to be able to disable the auto-repeat function of the keyboard, so that I can tell if the user is holding down the key, or pressing it several times.
    If you have found a solution please let me know at [email protected]
    Thanks,
    Ben Newton

  • Assigning multiple key press in shortcuts keyboard

    I find that i use the select all tracks forward far more than select track forward so would like to change my shortcuts to t for select all tracks and tt for select track. Problem is that I can't get Customize Keyboard to accept multiple presses of t - it simply registers the single press of t and asks if I want to change the shortcut it is assigned to.
    Any ideas?
    Thanks.

    Problem is, Redtruck, I can only get FCP to register one press of t. I can reasign select all tracks forward to a single t but when i go to select track forward and press t it asks me if i want to reassign t to this command and then overrides the select all forward shortcut (which reverts back to tttt automatically).
    I can't seem to find a way to enter multiple "t"s when assigning a shortcut.
    I hope this makes sense (I'm almost confusing myself).

  • Multiple key presses I'm stuck!!

    i want to make a hidden navigation thingy so that if the user
    types a word, but only the whole word it goes to next marker,
    i know the keyUp and KeyDown navigation but how do i make it
    only work when all have been pressed?
    Thank you

    How about storing the keystrokes in a global string?
    Something like this:
    on startMovie
    global gKeyString
    gKeyString = “”
    end
    on keyDown
    global gKeyString
    password = “abracadabra”
    gKeyString = gKeyString & _key.key
    if gKeyString.length > password.length then
    gKeyString = chars (gKeyString,
    gKeyString.length-password.length, gKeyString.length)
    end if
    if gKeyString = password then
    go frame “secretPlace”
    end if
    end
    I've not tested this code but it should work with little or
    no modification.

  • Non-repeating multiple key press issues

    My g/f has a G4 Titanium Onyx and seemingly randomly, the keyboard has started acting up.
    The bottom row of keys works, but anything above it gives out multiple characters on a single keypress. These are non-repetative. For example hitting 'l' doesn't cause 'llll' but '963.'
    The same keypress gives the same array of incorrect characters every time, but they don't seem to follow a pattern, one key even seems to work like the volume key.
    To the best of my knowledge it hasn't been dropped, had anything spilt on it, of been damaged in anyway since the last time it was working well.
    Any ideas as to what's causing this? The missus is most upset.

    Hi, Sam. Does "g/f" = "grandfather"?
    The behavior you describe is a new one on me.
    First check to make sure the Num Lock key isn't depressed (the light beside it should be lit if it is). With Num Lock depressed, the m, slash, j, k, l, semicolon, u, i, o, p, 7, 8, 9, and zero keys should produce numeric-keypad characters, and most of the others should produce nothing. That's not what you're seeing, but I suppose the Num Lock key might, if it's depressed, be modifying the way some other error or malfunction shows up. If it isn't depressed, try connecting an external USB keyboard and see whether that behaves the same way. If the external Kb works properly, the built-in keyboard is bad or not securely connected to the logic board. Release the keyboard latches and tip it back onto the palm rests, then disconnect and reconnect its ribbon cable connector. If there's no improvement, replace the keyboard or have Gramps use the external KB instead.
    If the problem occurs with the external KB too, boot to your OS install CD and try to set up and name a new admin user account. If you find that you can't do that because you can't type normally with either KB, even when booted to the CD, you have some hardware problem that's not in the KBs, and it may be time to have a technician look at the PB.

  • How to handle multiple key press in numeric keys

    I have used the code from eta . Code is somethg like tis
    lastKeyPress = System.currentTimeMillis();
    protected void keyPressed(int keyCode){
              boolean keyRepeated = false;
              if(System.currentTimeMillis() - lastKeyPress < 1000 &&
         lastKey == keyCode) {
              keyRepeated = true;
              lastKey = keyCode;
         lastKeyPress = System.currentTimeMillis();
    switch(keyCode) {
              case KEY_NUM0 :
              case KEY_NUM1 :
              case KEY_NUM2 :
              case KEY_NUM3 :
              case KEY_NUM4 :
              case KEY_NUM5 :
              case KEY_NUM6 :
              case KEY_NUM7 :
              case KEY_NUM8 :
              case KEY_NUM9 :
              case KEY_POUND :
                                  System.out.println(keyCode);
                                  System.out.println(keyRepeated + "     Repeat");
    But the 'keyRepeated ' always returning false. It doesnt satisfies the 'if' condition. So i m unable to differentiate btween 'a' ,'b' and 'c'. Pls any one take me to the correct solution

    sure pls follow this snippet
    private char getChar(int keyCode, boolean keyRepeated,int mode) {
    switch(keyCode) {
    case KEY_STAR :
    if(keyRepeated) {
         if(lastChar == symbols[0])
    return symbols[1];
    else if(lastChar == symbols[1])
    return symbols[2];
    else if(lastChar == symbols[2])
    return symbols[3];
    else if(lastChar == symbols[3])
    return symbols[4];
    else if(lastChar == symbols[4])
    return symbols[5];
    else if(lastChar == symbols[5])
    return symbols[6];
    else if(lastChar == symbols[6])
    return symbols[7];
    else if(lastChar == symbols[7])
    return symbols[8];
    else if(lastChar == symbols[8])
    return symbols[0];
    return symbols[0];
    case KEY_NUM1 :
    if(keyRepeated) {
    if(lastChar == '1')
    return symbols[0];
    else if(lastChar == symbols[0])
    return symbols[1];
    else if(lastChar == symbols[1])
    return symbols[2];
    else if(lastChar == symbols[2])
    return symbols[3];
    else if(lastChar == symbols[3])
    return symbols[4];
    else if(lastChar == symbols[4])
    return symbols[5];
    else if(lastChar == symbols[5])
    return symbols[6];
    else if(lastChar == symbols[6])
    return symbols[7];
    else if(lastChar == symbols[7])
    return symbols[8];
    else if(lastChar == symbols[8])
    return '1';
    return '1';
    case KEY_NUM2 :
         if(mode==LOWERALPHA){                 
         if(keyRepeated) {
         if(lastChar == 'c')
         lastChar = '2';
         else if(lastChar == '2')
         lastChar = 'a';
         else
         lastChar++;
         return lastChar;
         return 'a';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'C')
         lastChar = '2';
         else if(lastChar == '2')
         lastChar = 'A';
         else
         lastChar++;
         return lastChar;
         return 'A';           
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='2';
              else{
                   lastChar='2';                
              return lastChar;
    case KEY_NUM0 :
    if(keyRepeated) {
    if(lastChar == '0')
    lastChar = ' ';
    //else
    //lastChar++;
    return lastChar;
    return '0';
    case KEY_NUM3 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'f')
         lastChar = '3';
         else if(lastChar == '3')
         lastChar = 'd';
         else
         lastChar++;
         return lastChar;
         return 'd';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'F')
         lastChar = '3';
         else if(lastChar == '3')
         lastChar = 'D';
         else
         lastChar++;
         return lastChar;
         return 'D';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='3';
              else{
                   lastChar='3';                
              return lastChar;
    case KEY_NUM4 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'i')
         lastChar = '4';
         else if(lastChar == '4')
         lastChar = 'g';
         else
         lastChar++;
         return lastChar;
         return 'g';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'I')
         lastChar = '4';
         else if(lastChar == '4')
         lastChar = 'G';
         else
         lastChar++;
         return lastChar;
         return 'G';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='4';
              else{
                   lastChar='4';                
              return lastChar;
    case KEY_NUM5 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'l')
         lastChar = '5';
         else if(lastChar == '5')
         lastChar = 'j';
         else
         lastChar++;
         return lastChar;
         return 'j';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'L')
         lastChar = '5';
         else if(lastChar == '5')
         lastChar = 'J';
         else
         lastChar++;
         return lastChar;
         return 'J';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='5';
              else{
                   lastChar='5';                
              return lastChar;
    case KEY_NUM6 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'o')
         lastChar = '6';
         else if(lastChar == '6')
         lastChar = 'm';
         else
         lastChar++;
         return lastChar;
         return 'm';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'O')
         lastChar = '6';
         else if(lastChar == '6')
         lastChar = 'M';
         else
         lastChar++;
         return lastChar;
         return 'M';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='6';
              else{
                   lastChar='6';                
              return lastChar;
    case KEY_NUM7 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 's')
         lastChar = '7';
         else if(lastChar == '7')
         lastChar = 'p';
         else
         lastChar++;
         return lastChar;
         return 'p';
         }else if(mode==UPPERALPHA){
                   if(keyRepeated) {
         if(lastChar == 'S')
         lastChar = '7';
         else if(lastChar == '7')
         lastChar = 'P';
         else
         lastChar++;
         return lastChar;
         return 'P';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='7';
              else{
                   lastChar='7';                
              return lastChar;
    case KEY_NUM8 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'v')
         lastChar = '8';
         else if(lastChar == '8')
         lastChar = 't';
         else
         lastChar++;
         return lastChar;
         return 't';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'V')
         lastChar = '8';
         else if(lastChar == '8')
         lastChar = 'T';
         else
         lastChar++;
         return lastChar;
         return 'T';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='8';
              else{
                   lastChar='8';                
              return lastChar;
    case KEY_NUM9 :
         if(mode==LOWERALPHA){
         if(keyRepeated) {
         if(lastChar == 'z')
         lastChar = '9';
         else if(lastChar == '9')
         lastChar = 'w';
         else
         lastChar++;
         return lastChar;
         return 'w';
         }else if(mode==UPPERALPHA){
              if(keyRepeated) {
         if(lastChar == 'Z')
         lastChar = '9';
         else if(lastChar == '9')
         lastChar = 'W';
         else
         lastChar++;
         return lastChar;
         return 'W';
         }else if(mode==NUMERIC){
              if(keyRepeated)
                   lastChar='9';
              else{
                   lastChar='9';                
              return lastChar;
    default :
    return '\u200D';
    }

  • Thinkpad keyboard problem - some keys generate multiple keys when pressed

    thinkpad keyboard problem - some keys generate multiple keys when pressed
    For example, "t" generates "tr", "y" generates "yu", "backspace" generates "backspace" plus "IBM access connections", "m" generates "mn" and "n" generates "mn".  Not all keys are wrong. 
    For what it's worth, the odd behaviour started shortly after a trip to Miami in which I had a meeting at a cafe in which we were undercover but it was pouring cats and dogs - it was like having a meeting in a sauna - so I am wondering if the high humidity could have caused the behaviour.
    I tried replacing the keyboard but the new keyboard has the same problem.  
    The machine in question is a Thinkpad T23 running Windows XP Pro
    Any help would be appreciated as I am now in Los Angeles using a borrowed Mac! :-) 

    i have something along the lines of the same problem.
    http://bbs.archlinux.org/viewtopic.php?id=56777
    my conclusion is something in the last system update screwed it up.

  • Simulate multiple simultaneous key presses with applescript?

    Is it possible to simulate holding down multiple keys with applescript? No modifiers, just letters.
    For example;
    holding down d,o,n,k,e and y keys simultaneously for 1 second then letting go?
    so far I have this:
    on run {input, parameters}
              tell application "System Events"
           keystroke 4
           keystroke 1
           keystroke 37
           keystroke 9
           keystroke 2
           keystroke 17
              end tell
              return input
    end run
    Can anyone show me how to tell it to hold for 1 second, but more importantly is this actually possible and am I even on the right track?
    Cheers,
    Marty

    You should be able to achieve this via the key down and key up commands, rather than keystrokes.
    As the name implies, a keystroke is a simple, single press of a key whereas the key down simulates the pressing of a key and key up simulates the release.
    Off hand I have no idea how it will respond to multiple keys, and I'm not inclined to try, but this should point you in the right direction:
    tell application "System Events"
              key down "donkey"
      delay 1
              key up "donkey"
    end tell

  • Multiple key simultaneous presses

    Dear people
    please does anyone know using the key.isDown handle how many
    simultaneous key presses Actionscript 2 can handle, I can't get it
    to recognise more than 3 simultaneous max.

    I got this to work:
    //ctrl + shift + pageUp + pageDwn + End
    var myListener:Object = new Object();
    myListener.onKeyDown = function() {
    if ((Key.isDown(16)) && (Key.isDown(17)) &&
    (Key.isDown(33)) &&
    (Key.isDown(34)) && (Key.isDown(35))) {
    trace("here");
    Key.addListener(myListener);
    Dan Smith > adobe community expert
    Flash Helps >
    http://www.smithmediafusion.com/blog/?cat=11
    http://www.dsmith.tv
    "lajettee" <[email protected]> wrote in
    message
    news:funaeg$76s$[email protected]..
    > Dear people
    >
    > please does anyone know using the key.isDown handle how
    many simultaneous
    > key
    > presses Actionscript 2 can handle, I can't get it to
    recognise more than 3
    > simultaneous max.
    >
    >
    >
    > if ((Key.isDown(65)) && (Key.isDown(66))
    && (Key.isDown(67)) &&
    > (Key.isDown(68))) {
    >
    > .....do this.....
    >
    > }
    >

  • How to get Multiple Key Combinations

    Hi,
    I am trying to get the event for multiple key combinations, ie some thing like "*Ctrl + I + M*" or "*Alt + A + S + D*".
    For two key combinations ( like Ctrl+I or Ctrl+M) i am able to get, but for more than two keys combinations, can someone give an idea how to get it.
    I tried with both KeyCodeCombination and KeyCharacterCombination.
    Below is a quick example to check for the key combination demo.
    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.input.KeyCharacterCombination;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyCodeCombination;
    import javafx.scene.input.KeyCombination;
    import javafx.scene.input.KeyEvent;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    public class KeyCombinationDemo extends Application {
         Stage stage;
         Scene scene;
         StackPane root;
         public static void main(String[] args) {
              Application.launch(args);
         @Override
         public void start(Stage stage) throws Exception {
              this.stage = stage;
              root = new StackPane();
              root.getChildren().add(new Label("Enter any Key"));
              this.scene = new Scene(root, Color.LINEN);
              stage.setTitle(this.getClass().getSimpleName());
              stage.setWidth(600);
             stage.setHeight(600);
             stage.setScene(this.scene);
             stage.show();
              final KeyCombination keyComb1=new KeyCodeCombination(KeyCode.I,KeyCombination.CONTROL_DOWN);
              final KeyCharacterCombination keyComb2 = new KeyCharacterCombination("M",KeyCombination.CONTROL_DOWN);
              this.scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
                   @Override
                   public void handle(KeyEvent event) {
                        if(keyComb1.match(event)){
                             System.out.println("Ctrl+I pressed");
                        }else if(keyComb2.match(event)){
                             System.out.println("Ctrl+M pressed");
    }Thanks in Advance.
    Regards,
    Sai Pradeep Dandem.

    Hi John,
    Thanks for the prompt response.
    I tried the way you suggested and it worked well !! Thanks :)
    But, still i am expecting a direct way to handle this. :p
    Anyway here is code which i modified accordingly
    final String keyCombination1 = "_ALT_E_O";
    final String keyCombination2 = "_ALT_E_P";
    final String keyCombination3 = "_CONTROL_H";
    final StringBuilder key = new StringBuilder();
    this.scene.addEventHandler(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
         @Override
         public void handle(KeyEvent event) {
              String codeStr = event.getCode().toString();
              if(!key.toString().endsWith("_"+codeStr)){
                   key.append("_"+codeStr);
    this.scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {
         @Override
         public void handle(KeyEvent event) {
              if(key.length()>0){
                   if(key.toString().equals(keyCombination1)){
                        System.out.println("Key Combination 1 pressed");
                   }else if(key.toString().equals(keyCombination2)){
                        System.out.println("Key Combination 2 pressed");
                   }else if(key.toString().equals(keyCombination3)){
                        System.out.println("Key Combination 3 pressed");
                   key.setLength(0);
    });Thanks & Regards,
    Sai Pradeep Dandem

  • How do you clear the buffer of excess key presses, in Java?

    Right now, in the game I am working on, if the user presses a key multiple times the actions will be performed as many times as it registers, even though I disallow key presses during the time that the action is taking place.
    For example, a move of 1 space can be carried out with a key press. While the character is moving, key presses are not allowed. However, if you just press the key 5 or 25 times, the character will just keep moving, once he's done with the first one.
    What I need to do is clear the buffer of key presses after an action has taken place, so that the excess keys are not registered. I know the commands to do so in C++, but not in Java.

    Well, I think you've got what I was saying backwards, or I'm not understanding what you are asking correctly.
    it is suppposed to return if isMoving is true, not false. If isMoving is true, it means that the moving animation, and actions are taking place, Which is a process that take about a second, for the player to move one space.
    Here's the code where I process the keypresses
    private void processKey(KeyEvent e) {
        if (isMoving) {return;}
        int keyCode = e.getKeyCode();
        if (!isPaused && !gameOver) {
            isMoving = true;
          if (keyCode == KeyEvent.VK_UP) {
            player.move(player.NE);
          else if (keyCode == KeyEvent.VK_DOWN) {
            player.move(player.SW);
          else if (keyCode == KeyEvent.VK_LEFT) {
            player.move(player.NW);
          else if (keyCode == KeyEvent.VK_RIGHT) {
            player.move(player.SE);
            isMoving = false;
    }And in case I need to clear up what I want to happen, and the results I'm seeing. The player, in this case, moves one space in a direction, with a single press of an arrow key. That functionality is working fine, as intended. However, I don't want you to press the key twice quickly and move two spaces. I don't want you to hold down an arrow key and move continually.
    That part of the functionality is what is not working.
    As I understand my code, pressing the key once should set isMoving to true and, therefore further presses shouldn't register until isMoving is false again, which shouldn't happen until the player moves have finished.
    But, the way that it is working now is that if I press the key 2, 3 or 20 times, as soon as one move is finished another begins. Are the key presses just sitting in the buffer somewhere waiting for isMoving to become false again? And if so, is there a function I can call to clear that buffer after a move is finished?

Maybe you are looking for