How boolean value here becomes false

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(); // boolean variable if( doPrint ) { try { job.print(); } catch( PrinterException exc) { System.out.println( exc ); } } else { System.out.println("You cancelled the print"); } } }); 

}

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:

enter image description here

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

}

0
source share
1 answer

In the API, the print dialog is handled by the operating system, not the JVM, so I'm not completely surprised that different people with different settings may have different results. I suggest you try running it using an actual printer and see what happens.

0
source

Source: https://habr.com/ru/post/893809/


All Articles