javafxkeyboardnumpad

Using javaFx, how to distinguish between return-key and enter-key on the numpad?


Using javaFx, how to distinguish between return-key and enter-key on the numpad?

This is a near duplicate of Java/AWT/Swing: how to distinguish the pressed enter or return key , but for javaFX.

Unfortunately, in javaFX, there is no KeyEvent.KEY_LOCATION_NUMPAD.


Solution

  • String properties of KeyEvent might contain some useful information.

    The event.getText() resulted in different values for return and numpad enter keys in my tests (openjfx 21.0.2).

    import javafx.application.Application;
    
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyEvent;
    import javafx.stage.Stage;
    
    public class Enters extends Application {
    
        private static final int RETURN_KEY_CODE = 13;
    
        @Override
        public void start(Stage stage) {
            Label label = new Label("Press the keys");
            label.setPadding(new Insets(50));
            stage.setScene(new Scene(label));
    
            stage.addEventFilter(KeyEvent.KEY_PRESSED, e -> {
                if (e.getCode() != KeyCode.ENTER) {
                    return;
                }
                int textCh = (e.getText().length() > 0) ? e.getText().charAt(0) : -1;
                int ch = (e.getCharacter().length() > 0) ? e.getCharacter().charAt(0) : -1;
                boolean keypadEnter = (textCh != RETURN_KEY_CODE);
                
                System.out.println(String.format(
                        "%sENTER\tTextCode:%s CharCode:%s",
                        (keypadEnter ? "NUMPAD " : ""), textCh, ch));
            });
            stage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    
    ENTER   TextCode:13 CharCode:0
    ENTER   TextCode:13 CharCode:0
    NUMPAD ENTER    TextCode:-1 CharCode:0
    ENTER   TextCode:13 CharCode:0
    NUMPAD ENTER    TextCode:-1 CharCode:0
    

    There is no guarantee that this is platform independent or that field population won't change in the future versions.