Issue
I thought I found the answer with deselect()
but strangely it doesn't do anything, the text is still all selected on opening.
TextInputDialog textInput = new TextInputDialog("whatever text");
textInput.initOwner(sentence.stage);
Optional<String> result = textInput.showAndWait();
if (result.isPresent()) {
// process
}
textInput.getEditor().deselect();
Solution
The Dialog#showAndWait()
method does not return until the dialog is closed. That means your call to deselect()
is too late. However, simply reordering your code does not appear to solve your problem. This looks like a timing issue; the text is probably selected when the field gains focus so you need to deselect the text after that happens. For example:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextInputDialog;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
var button = new Button("Show dialog...");
button.setOnAction(
ae -> {
var textInput = new TextInputDialog("Some text");
textInput.initOwner(primaryStage);
Platform.runLater(textInput.getEditor()::deselect);
textInput.showAndWait();
});
var root = new StackPane(button);
primaryStage.setScene(new Scene(root, 500, 300));
primaryStage.show();
}
}
The Runnable
passed to runLater
is executed after the dialog is shown and after the text has been selected.
Answered By - Slaw