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

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

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

最新更新