This is a print button action listener
public void hookUpEvents() { print.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable( new Printer() ); boolean doPrint = job.printDialog();
}
When I compile this fragment with the whole code, the print button is displayed. The above is the equalizer of the print button. A.
When I click the Print button, the following dialog box is displayed:

Automatically after 3-4 seconds Cancel printing to CMD. How did this happen? And when I click Cancel, nothing is displayed. Like the job.printDialog(); operator job.printDialog(); returns false on its own?
full code
// Program to print simple text on a Printer import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.print.PrinterException; import java.awt.print.*; class Printer extends JPanel implements Printable { JButton print; Printer() { buildGUI(); hookUpEvents(); } public void buildGUI() { JFrame fr = new JFrame("Program to Print on a Printer"); JPanel p = new JPanel(); print = new JButton("Print"); p.setBackground( Color.black ); fr.add(p); p.add( print , BorderLayout.CENTER ); this.setPreferredSize( new Dimension ( 300,200 ) ); fr.pack(); fr.setVisible( true );
}
public void hookUpEvents() { print.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable( Printer.this ); boolean doPrint = job.printDialog(); // PageFormat pf = job.pageDialog(job.defaultPage()); if( doPrint ) { try { job.print(); } catch( PrinterException exc) { System.out.println( exc ); } } else { System.out.println("You cancelled the print"); } } }); } public int print( Graphics g , PageFormat pf , int pageIndex) throws PrinterException{ return PAGE_EXISTS; } public static void main( String args[] ) { new Printer(); }
}
source share