对于您描述的用例,您可以只使用Dialog API,或作为其中一部分的专用Alert 类。
对于您提出的更一般的问题:
我想知道是否有办法发送参数和更改舞台/场景
这样做的方法是使用文档中描述的custom component 机制。
简而言之,创建一个加载 FXML 文件并定义所需属性的 UI 类型的子类,例如
public class ExceptionPane extends BorderPane {
private final ObjectProperty<Exception> exception ;
public ObjectProperty<Exception> exceptionProperty() {
return exception ;
}
public final Exception getException() {
return exceptionProperty().get();
}
public final void setException(Exception exception) {
exceptionProperty().set(exception);
}
@FXML
private final TextArea stackTrace ;
@FXML
private final Label message ;
public ExceptionPane() throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/fxml"));
loader.setRoot(this);
loader.setController(this);
loader.load();
exception.addListener((obs, oldException, newException) -> {
if (newException == null) {
message.setText(null);
stackTrace.setText(null);
} else {
message.setText(newException.getMessage());
StringWriter sw = new StringWriter();
newException.printStackTrace(new PrintWriter(sw));
stackTrace.setText(sw.toString());
}
});
}
}
然后使用 "dynamic root" 定义 FXML:
<!-- imports etc -->
<fx:root type="BorderPane" ...>
<center>
<TextArea fx:id="stackTrace" editable="false" wrapText="false" />
</center>
<top>
<Label fx:id="message" />
</top>
</fx:root>
现在您可以直接在 Java 或 FXML 中使用它:
try {
// some code...
} catch (Exception exc) {
ExceptionPane excPane = new ExceptionPane();
excPane.setException(exc);
Stage stage = new Stage();
stage.setScene(new Scene(excPane));
stage.show();
}
或
<fx:define fx:id="exc"><!-- define exception somehow --></fx:define>
<ExceptionPane exception="${exc}" />