I'm writing an application in JavaFX and would like to create a function that waits for the user to enter text into my TextField
and hit Enter
before returning (continuing).
private void setupEventHandlers() {
inputWindow.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent e) {
if (e.getCode().equals(KeyCode.ENTER)) {
inputWindow.clear();
}
}
});
}
Here I clear the text in my TextField
when the user hits the Enter key.
Any ideas?
Edit: I'll clarify exactly what I'm looking for:
private void getInput() {
do {
waitForEventToFire();
}
while (!eventFired);
}
Obviously this is just pseudocode, but this is what I'm looking for.
I would have liked to use ControlsFx, but I was not able to upgrade to a Java 1.8 runtime so had to build a dialog component from scratch. Here's what I came up with:
My test harness looks like this, so you can run the above code fairly quickly:
Sample Solution
Perhaps what you want to do is display a prompt dialog and use showAndWait to await for a response from the prompt dialog before continuing. Similar to JavaFX2: Can I pause a background Task / Service?
Likely your situation is a bit simpler than the background task service and (unless you have a long running task involved), you can just do everything on the JavaFX application thread. I created a simple sample solution which just runs everything on the JavaFX application thread
Here is the output of the sample program:
Every time some missing data is encountered, a prompt dialog is shown and awaits user input to fill in the missing data (user provided responses are highlighted in green in the screenshot above).
Existing Prompt Dialog Library
There is a pre-written prompt dialog in the ControlsFX library which will handle the prompt dialog display for you.
Clarifying Event Handler Processing and Busy Waiting
You would like:
By definition, that is what an EventHandler is. An EventHandler is "invoked when a specific event of the type for which this handler is registered happens".
When the event occurs, your event handler will fire and you can do whatever you want in the event handler - you don't need, and should never have a busy wait loop for the event.
Creating a TextField action event handler
Instead of placing the event handler on the window as you have in your question, it is probably better to use a specific action event handler on your text field using textField.setOnAction:
If you place the text field in a dialog with a default button set for the dialog, setting an event handler for the text field is unnecessary as the dialog's default button will pick up and process the enter key event appropriately.