KeyEvent generated three times for single key release

135 views Asked by At

I'm writing an application that should respond to zoom commands and I'd like those to be triggered by the keyboard too (e.g., CMD/CTRL and + (or =) for zoom in). I got this working fine, apart from one strange thing: the key event for the '=' key (the normal one, at the top of the keyboard, next to the number and '-' keys), is generated three times when I hold the CMD key (I'm on a Mac). Strangely enough this doesn't happen when you don't hold the CMD key…

Below program shows what I mean:

package test_keypress;

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Test_KeyPress extends Application {

    static int nr = 0;

    public void start(Stage stage) {

        VBox root = new VBox();
        root.setAlignment(Pos.CENTER);
        Label label = new Label("Press Key");
        Label keyReleasedTxt = new Label();
        root.getChildren().addAll(label, keyReleasedTxt);
        Scene scene = new Scene(root, 400, 300);

        scene.setOnKeyReleased((KeyEvent e) -> {
            keyReleasedTxt.setText("Key Released: " + e.getCode() + " = " + e.getText());
            System.out.println("Key Released: " + e.getCode() + " = " + e.getText());
            e.consume();
        });

        stage.setTitle("Key Event test");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

This is the output it generates:

Key Released: EQUALS = = <= pressing just the '=' key on the keyboard

Key Released: EQUALS = = Key Released: EQUALS = + Key Released: EQUALS = = Key Released: COMMAND = <= when '=' is pressed together with the CMD key.

Any idea what's going on here, and how I can prevent this from happening?

Note: the numeric keypad versions of the +, - and = keys behave just fine, and so do the other keys I have tried so far; it is just the “normal” '=' key that behaves this strangely.

0

There are 0 answers