Umbrella_Programmer
Umbrella_Programmer

Reputation: 191

Document still printing even when print dialog is Cancelled or closed with X button?

My program has a Print Image button that sends the contents of the imageView node to the printer. The button causes the print dialog to display.

The problem is, inside the dialog, regardless of whether you press Print, Cancel, or the X button, the document still prints. How do I fix this so the document only prints after confirming within the print dialog?

// 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();
        }
    }
}

Upvotes: 0

Views: 225

Answers (1)

Umbrella_Programmer
Umbrella_Programmer

Reputation: 191

The solution was to note that showPrintDialog() returns a boolean value that can be handled via an if-else block:

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

Upvotes: 1

Related Questions