Question

I'm creating a game using JavaFX8 that presents choices in a TextFlow and waits for the user to input a specific key then changes the text.

For example: Create Character? (C)ontinue (E)xit

The user presses 'C' on their keyboard and the following is displayed: Choose gender. (M)ale (F)emale (B)ack

Pressing 'M' proceeds to next screen and so on. 'B' takes them back to the Create Character "state".

There is no other user input available. No buttons, no text areas, nothing. They just press a key and it changes the text in the TextFlow.

I have an EventHandler that is registering key presses correctly and placing the result in a static String field so it can be accessible by any method in the class. Is there a way to check that variable inside a method? It waits for user to press a key, checks value against array of valid values (based on the choices displayed in the TextFlow), returns it or keeps checking.

infinite while loops cause the program to crash. This is asynchronous as the user could press a valid/invalid key at any time.

I've looked into JavaFX concurrency (Task, Service, Worker) but it seems too complicated for me at this point. Maybe there is a simpler way that I have overlooked?

Here is some code for my EventHandler which works just fine.

static String userInput = "";
static EventHandler<KeyEvent> keyEvent=null;

public void start(Stage stage) {

        /*bunch of code*/
        keyEvent = new EventHandler<KeyEvent>(){
            public void handle(KeyEvent ke)
            {
                userInput = String.valueOf(ke.getCharacter());
                System.out.print(userInput);
            }
        };
        scene.setOnKeyTyped(keyEvent);
}
Was it helpful?

Solution

create a method...such like...

void readInputCharacter(char ch){
    //code to determine what to do with this input
    //end with a check to see if there was valid input, if so redraw the text
}

then call this method from you handler there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top