即使使用X按钮取消或关闭了打印对话框,文档仍在打印吗?

时间:2019-03-04 23:53:48

标签: java javafx printing fxml

我的程序有一个“打印图像”按钮,可将imageView节点的内容发送到打印机。该按钮将导致显示打印对话框。

问题是,在对话框内,无论您按打印,取消还是X按钮,文档仍会打印。如何解决此问题,以便仅在打印对话框中确认后才打印文档?

// a method that allows user to print the contents of the ImageView node
@FXML
private void printImageView(ActionEvent event) {
    if (imageDisplay.getImage() == null) {
        event.consume();
        return;
    } else {
        // create a new image view node and send the image there
        ImageView printedImageView = new ImageView();
        printedImageView.setImage(imageDisplay.getImage());

        // instantiate a printer object
        PrinterJob printerJob = PrinterJob.createPrinterJob();

        // show the print dialog
        final Scene scene = textArea.getScene();
        final Window owner = scene.getWindow();
        printerJob.showPrintDialog(owner);

        // end the job if print is successful
        boolean successfullyPrinted = printerJob.printPage(printedImageView);
        if (successfullyPrinted) {
            printerJob.endJob();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

解决方案是注意showPrintDialog()返回一个布尔值,可以通过if-else块进行处理:

// print the image only if user clicks OK in print dialog
        boolean userClickedOK = printerJob.showPrintDialog(owner);
        if (userClickedOK) {
            printerJob.printPage(printedImageView);
        } else {
            printerJob.cancelJob();
        }