The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.print  [6 examples]

e705. Cancelling a Print Job

Not all print jobs can be cancelled. A print job can be cancelled if the PrintJob object implements CancelablePrintJob. This example shows a cancel button if the print job can be cancelled.
    try {
        // Create the print job
        final DocPrintJob job = service.createPrintJob();
        Doc doc = new SimpleDoc(is, flavor, null);
    
        // Monitor print job events.
        // See e702 Determining When a Print Job Has Finished
        // for the implementation of PrintJobWatcher.
        PrintJobWatcher pjDone = new PrintJobWatcher(job);
    
        // Sample code to display a cancel button
        JFrame frame = new JFrame();
        if (job instanceof CancelablePrintJob) {
            JButton btn = new JButton("Cancel Print Job");
            btn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CancelablePrintJob cancelJob = (CancelablePrintJob)job;
                    try {
                        cancelJob.cancel();
                    } catch (PrintException e) {
                        // Possible reason is job was already finished
                    }
                }
            });
    
            frame.getContentPane().add(btn, BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
        }
    
        // Print it
        job.print(doc, null);
    
        // Wait for the print job to be done
        pjDone.waitForDone();
    
        // Remove frame
        frame.setVisible(false);
    
        // It is now safe to close the input stream
        is.close();
    } catch (PrintException e) {
        if (e.getCause() instanceof java.awt.print.PrinterAbortException) {
            // Print job was cancelled
        }
    }

 Related Examples
e700. The Quintessential Printing Program Using a Printing Service
e701. The Quintessential Printing Program Using a Streaming Printing Service
e702. Determining When a Print Job Has Finished
e703. Discovering Available Print Services
e704. Discovering Available Streaming Print Services


© 2002 Addison-Wesley.