Java examples for 2D Graphics:Print
Cancelling a Print Job
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.print.CancelablePrintJob; import javax.print.DocPrintJob; import javax.print.PrintException; import javax.print.PrintService; import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { try {//w ww .j a v a 2s . c o m // Create the print job PrintService service = null; final DocPrintJob job = service.createPrintJob(); // 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); // Remove frame frame.setVisible(false); } catch (Exception e) { if (e.getCause() instanceof java.awt.print.PrinterAbortException) { // Print job was cancelled } } } }