JavaFx 当我打开 dialog.showAndWait() 如何聚焦 TextArea
JavaFx when I open dialog.showAndWait() how to focus TextArea
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);
textArea.requestFocus();
dialog.showAndWait();
});
root.getChildren().add(button);
return root;
}
我尝试在 dialog.showAndWait();
之前使用 textArea.requestFocus();
但是当对话框打开时它总是
焦点确定按钮。如何在对话框首次打开时聚焦 textArea?
这应该可以解决问题:
dialog.setOnShown(event -> {
Platform.runLater(textArea::requestFocus);
event.consume();
});
dialog.showAndWait();
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);
textArea.requestFocus();
dialog.showAndWait();
});
root.getChildren().add(button);
return root;
}
我尝试在 dialog.showAndWait();
之前使用 textArea.requestFocus();
但是当对话框打开时它总是
焦点确定按钮。如何在对话框首次打开时聚焦 textArea?
这应该可以解决问题:
dialog.setOnShown(event -> {
Platform.runLater(textArea::requestFocus);
event.consume();
});
dialog.showAndWait();