How does boolean here become false on its own
This is action listener of print button
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 snippet along with whole code , print button gets displayed . The above is the action listener of the print button.
As i click the print button this dialog box is displayed :
Automatically after 3-4 seconds You cancelled the print is displayed on the cmd.
How does this happen ? And when i click cancel nothing is displayed.
How can the statement job.printDialog();
return false on its own ?
complete 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();
}
}
Per the API, the print dialog is handled by the operating system, not the JVM, so I'm not completely surprised that different folks with different set ups could have different results. I suggest you try running it with an actual printer and see what happens.
精彩评论