so8857
so8857

Reputation: 351

How to get user input using KeyCombination in JavaFX?

I am working on a simple in-fix to post-fix converter. I want to get the user's input from the keyboard. To enter some symbols, e.g."+", the user must press shift. I am using a KeyCombination object to capture whether the user is using shift or not.

My code keeps give me this error: Key code must not match modifier key!

However, when I look at the keycode, it is not Shift, rather it is whatever number row key is pressed. E.g., if the user presses Shift + =, the keycode is EQUALS, not the Shift_DOWN modifier. The code works as expected, but I can't figure out how to get rid of this exception.

tfInput.setOnKeyPressed(e -> {

        if (e.isShiftDown()) {
            KeyCombination kc = new KeyCodeCombination(e.getCode(),
                    KeyCombination.SHIFT_DOWN);
            userInput = kc.toString();  
        }

Upvotes: 1

Views: 949

Answers (1)

Matt
Matt

Reputation: 3187

The reason you are getting the error is because the first parameter in key combination is keycode and shift is a key modifier you can stop getting this error by checking if the key is SHIFT before you continue

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.stage.Stage;

public class Main extends Application {

    private String userInput;

    @Override
    public void start(Stage stage) {
        TextField textField = new TextField();

        textField.setOnKeyPressed(e -> {
            System.out.println(e.getCode());
            if (e.isShiftDown()&&!e.getCode().toString().equals("SHIFT")) {
                KeyCombination kc = new KeyCodeCombination(e.getCode(), KeyCombination.CONTROL_ANY);
                userInput = kc.toString();
                System.out.println(userInput);
            }
        });

        Scene scene = new Scene(textField);
        stage = new Stage();
        stage.setScene(scene);
        stage.show();
    }

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

Upvotes: 1

Related Questions