首页 > 解决方案 > JavaFX 在打开新的 TextInputDialog 时取消选择文本

问题描述

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

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

标签: javajavafx

解决方案


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

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

在显示对话框选择文本之后执行Runnable传递给。runLater


推荐阅读