JavaFX 在打开新的 TextInputDialog 时取消选择文本

JavaFX deselect text upon opening new TextInputDialog

我以为我找到了 deselect() 的答案,但奇怪的是它什么也没做,打开时文本仍然全部被选中。

TextInputDialog textInput = new TextInputDialog("whatever text");
textInput.initOwner(sentence.stage);
Optional<String> result = textInput.showAndWait();
if (result.isPresent()) {
   // process
}
textInput.getEditor().deselect();

在对话框关闭之前,Dialog#showAndWait() 方法不会return。这意味着您对 deselect() 的调用为时已晚。但是,简单地重新排序您的代码似乎并不能解决您的问题。这看起来像是一个时间问题;当字段获得焦点时,文本可能已被选中,因此您需要取消选择 after 发生的文本。例如:

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();
  }
}

传递给 runLaterRunnable 在显示对话框后执行 并且 在选择文本后执行。