Java Reference
In-Depth Information
is to make sure the PrinterJob object that controls the printing process works with a PageFormat object
that has the orientation set the way that you want.
If you had known ahead of time, back in the actionPerformed() method in the FileAction inner class
to SketcherFrame , you could have set up the PageFormat object for the print job before the print() meth-
od for the view object ever gets called. You can still do this by modifying the code that initiates printing in
the actionPerformed() method like this:
// Get a printing object
PrinterJob printJob = PrinterJob.getPrinterJob();
PrintService printer = printJob.getPrintService();
if(printer == null) {
JOptionPane.showMessageDialog(SketcherFrame.this,
"No default printer available.",
"Printer Error",
JOptionPane.ERROR_MESSAGE);
return;
}
PageFormat pageFormat = printJob.defaultPage();
Rectangle rect = theApp.getModel().getModelExtent(); // Get sketch bounds
// If the sketch width is greater than the height, print landscape
if(rect.width>rect.height) {
pageFormat.setOrientation(PageFormat.LANDSCAPE);
}
printJob.setPrintable(theApp.getView(), pageFormat);
if(printJob.printDialog()) { // Display print
dialog
try { // and if true is
returned...
printJob.print(); // ...then print
} catch(PrinterException pe) {
System.out.println(pe);
JOptionPane.showMessageDialog(SketcherFrame.this,
"Error printing a sketch.",
"Printer Error",
JOptionPane.ERROR_MESSAGE);
}
Directory "Sketcher 8 printing landscape automatically"
Calling the defaultPage() method for a PrinterJob object returns a reference to the default page for the
current printer. You can then change that to suit the conditions that you want to apply in the printing oper-
ation and pass the reference to an overload of the setPrintable() method. The call to setPrintable()
here makes the printJob object use the SketcherView object as the Printable object, and supplies the
PageFormat object to be used when the print() method for the view is called. With this code you don't
need to worry about the orientation in the print() method for the Printable object. It is taken care of be-
fore print() ever gets called.
Search WWH ::




Custom Search