JavaFX调用dialog.showAndWait()打开对话框时如何默认聚焦TextArea
问题原因
现有代码中直接在dialog.showAndWait()前调用textArea.requestFocus()无效,是因为此时Dialog尚未完成界面初始化与场景挂载,TextArea还不具备接收焦点的条件,Dialog渲染完成后会自动将默认焦点分配给确认按钮,覆盖之前的焦点请求。
解决方案
监听Dialog的onShown事件,待对话框完全展示、所有界面元素挂载完成后再执行焦点设置即可,修改后的核心代码如下:
public Node dialog(){ Pane root = new Pane(); root.setPrefWidth(200); root.setPrefHeight(200); Button button = new Button("Dialog"); button.setOnAction(event -> { Dialog dialog = new Dialog(); TextArea textArea = new TextArea(); dialog.getDialogPane().setContent(textArea); ButtonType ok = new ButtonType("OK", ButtonBar.ButtonData.OK_DONE); ButtonType cancel = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE); DialogPane dialogPane = dialog.getDialogPane(); dialogPane.getButtonTypes().addAll(ok, cancel); // 新增监听对话框展示事件,展示完成后设置焦点 dialog.setOnShown(e -> { textArea.requestFocus(); }); dialog.showAndWait(); }); root.getChildren().add(button); return root; }
如果特殊场景下上述方案仍不生效,也可以改用Platform.runLater包裹焦点请求,放在dialog.showAndWait()前执行即可:
// 需要先导入import javafx.application.Platform; Platform.runLater(() -> textArea.requestFocus());
内容的提问来源于stack exchange,提问作者Lson
相关产品推荐
相关产品推荐

