繁体   English   中英

JavaFX - 使用fxml创建自定义对话框

[英]JavaFX - creating custom dialogs using fxml

我是javafx的新手,我正在尝试创建自定义对话框/警报。 问题是我正在使用Scene Builder来设计GUI,我想在每次加载fxml文件时修改对话框(即更改标题,标签文本等),所以我想知道是否有发送参数和修改舞台/场景的方式,或者我可以实现的任何其他方式。

更具体地说,假设我想在程序中的任何地方处理错误,所以我加载了一个新的fxml文件,代表我创建的错误对话框,并根据我需要的错误类型修改其中的组件处理,类似于,例如,在swing中的JOptionPane.showMessageDialog(...)。

对于您描述的用例,您可以使用Dialog API或属于它的专用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());
            }
        });
    }
}

然后使用“动态根”定义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}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM