Java Reference
In-Depth Information
We need to add the
printWindowAction
member to the class so change the declaration for the file
action members of the
SketchFrame
class to:
private FileAction newAction, openAction, closeAction, saveAction,
saveAsAction, printAction, printWindowAction;
Because our new menu item is a
FileAction
object, events originating from it will invoke the handler
that we defined in the
FileAction
inner class. We need to add some code to the
actionPerformed()
method in the inner class to deal with them. Add the following code after the
if
that handles the
printAction
events:
} else if(name.equals(printWindowAction.getValue(NAME))) {
PrinterJob printJob = PrinterJob.getPrinterJob(); // Get a print job
PrintService printer = printJob.getPrintService();
PrintRequestAttributeSet printAttr =
new HashPrintRequestAttributeSet();
if(printer == null) {
JOptionPane.showMessageDialog(SketchFrame.this,
"No default printer available.",
"Printer Error",
JOptionPane.ERROR
_
MESSAGE);
return;
}
PageFormat pageFormat = printJob.defaultPage(); // and default format
// The app window is the page source
printJob.setPrintable(theApp.getWindow(),pageFormat);
if(printJob.printDialog(printAttr)) { // Display print dialog
// If true is returned...
try {
printJob.print(printAttr); // ...then print
} catch(PrinterException pe) {
JOptionPane.showMessageDialog(SketchFrame.this,
"Error printing the window.",
"Printer Error",
JOptionPane.ERROR
_
MESSAGE);
}
}
}
The application window, which is the
SketchFrame
object,
window
, is responsible for printing the
window because it is obviously best placed to do this, so we must make the
SketchFrame
class
implement the
Printable
interface. Change the first line of the class definition to:
public class SketchFrame extends JFrame
implements Constants, ActionListener, Observer, Printable
Now we can add the definition of the
print()
method to the class: