我是 javafx 新手,我试图创建自定义对话框/警报。问题是我正在使用 Scene Builder 来设计 GUI,并且我想在每次加载 fxml 文件时修改对话框(即更改标题、标签文本等),所以我想知道是否有发送参数和修改舞台/场景的方式,或者我可以实现这一点的任何其他方式。
更具体地说,假设我想在程序中的任何位置处理一个错误,因此我加载一个新的 fxml 文件来表示我创建的错误对话框,然后根据我需要的错误类型修改其中的组件处理,类似于 swing 中的 JOptionPane.showMessageDialog(...) 。
对于您描述的用例,您可以只使用DialogAPI 或Alert其中的专用类。
对于您提出的更普遍的问题:
我想知道是否有办法发送参数并更改舞台/场景
做到这一点的方法是使用文档中描述的自定义组件机制。
简而言之,创建您需要的 UI 类型的子类来加载 FXML 文件,并定义您需要的属性,例如
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());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用“动态根”定义 FXML :
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());
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以直接在 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();
}
Run Code Online (Sandbox Code Playgroud)
或者
<!-- imports etc -->
<fx:root type="BorderPane" ...>
<center>
<TextArea fx:id="stackTrace" editable="false" wrapText="false" />
</center>
<top>
<Label fx:id="message" />
</top>
</fx:root>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14514 次 |
| 最近记录: |