Java Reference
In-Depth Information
private HashPrintRequestAttributeSet requestAttr =
new HashPrintRequestAttributeSet();
There are other
HashPrintRequestAttributeSet
class constructors that will create non-empty
attribute sets but this will suffice for our needs. You will need an import statement for the class in the
SketchFrame.java
file:
import javax.print.attribute.HashPrintRequestAttributeSet;
Now we have a print request attribute set object, we can modify the
actionPerformed()
method in
the
FileAction
inner class to use the Java print dialog:
// Get a printing object
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService printer = printJob.getPrintService();
if(printer == null) {
JOptionPane.showMessageDialog(SketchFrame.this,
"No default printer available.",
"Printer Error",
JOptionPane.ERROR
_
MESSAGE);
return;
}
// The view is the page source
printJob.setPrintable(theApp.getView());
HashPrintRequestAttributeSet printAttr = new HashPrintRequestAttributeSet();
if(printJob.printDialog(printAttr)) { // Display print dialog
// If true is returned...
try {
printJob.print(printAttr); // then print
} catch(PrinterException pe) {
System.out.println(pe);
JOptionPane.showMessageDialog(SketchFrame.this,
"Error printing a sketch.",
"Printer Error",
JOptionPane.ERROR
_
MESSAGE);
}
}
Note that we also use an overloaded version of the
print()
method for the
PrinterJob
object to which
we pass the print request attribute set. Thus the print operation will use whatever attributes were set or
modified in the print dialog displayed by the
printDialog()
method. If you run Sketcher with these
changes you should see a dialog with three tabs similar to that shown below when you print a sketch: