Question

I am doing an homework in JavaFX2.1 and I have a problem with the setOnKeyPressed method. My programs simulates a piano, so it does a sound every time I click on a button: 'Q' is 'do', 'W' is 're' and so on... I also have (for now) a mouse input, which will be disabled later since I can't play several notes at once with it...

My problem: if I hold down a key (on the keyboard of course, not with the mouse) its associated event will be triggered in a loop... I did several tests and noticed that only the setOnKeyPressed is triggered, not the setOnKeyReleased.

I did some workarounds but they are not doing what I expect:

  • adding a boolean value to know if the key has been released disables the possibility of pushing on multiple keys at once.
  • turning off the volume after the sound has been played (and putting it back to its value when the key is released) seems to work, also for multiple keys, BUT the duration of the sound is considerably shorter compared to when I hold down the mouse on the same key.

Any suggestions?

Was it helpful?

Solution

You can't disable multiple events as it's system behavior. The best solution for you would be to improve boolean flag approach to store flag for each key. E.g. next way:

    final Set<String> pressedKeys = new HashSet<String>();

    keyboard.setOnKeyPressed(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent t) {
            String note = t.getText();
            if (!pressedKeys.contains(note)) {
                // you may need to introduce synchronization here
                pressedKeys.add(note);

                playNote(note);
            }
        }
    });
    keyboard.setOnKeyReleased(new EventHandler<KeyEvent>() {

        @Override
        public void handle(KeyEvent t) {
            pressedKeys.remove(t.getText());
        }
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top