我的程序有一个“打印图像”按钮,可将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();
        }
    }
}

最佳答案

解决方案是注意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();
        }

09-28 09:58