javajavafx-2autorepeat

Disable auto-repetition of setOnKeyPressed (JavaFX 2.1)


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:

Any suggestions?


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());
            }
        });