Java Reference
In-Depth Information
Let's now implement the Pageable interface in the SketchView class. We must add three methods to the
class getNumberOfPages() that returns the number of pages to be printed, getPrintable() that
returns a reference to the Printable object that will print a page with a given index, and
getPageFormat() that returns a reference to a PageFormat object corresponding to a particular page.
import javax.swing.*;
import java.awt.*;
import java.util.*; // For Observer
import java.awt.event.*; // For events
import javax.swing.event.*; // For mouse input adapter
import java.awt.geom.*;
import java.awt.print.*;
class SketchView extends JComponent
implements Observer,
Constants,
ActionListener,
Printable,
Pageable {
// Always two pages
public int getNumberOfPages() {
return 2;
}
// Return the Printable object that will render the page
public Printable getPrintable(int pageIndex) {
if(pageIndex == 0) // For the first page
return new SketchCoverPage(theApp); // return the cover page
else
return this;
}
public PageFormat getPageFormat(int pageIndex) {
// Code to define the PageFormat object for the page...
}
public int print(Graphics g,
PageFormat pageFormat,
int pageIndex)
throws PrinterException {
// Revised printing code...
}
// Plus the rest of the class as before...
}
The first two methods are already implemented here. We will always print two pages, the first page
being printed by a SketchCoverPage object and the second page by the view object. Since we are
providing custom PageFormat objects for each page, we will need to amend the print() method in
SketchView to just use the PageFormat object it gets. First, let's see how we can produce the
PageFormat object for a page. To make use of some of the methods we have discussed, we will double
the size of the margins for the cover page but leave the margins for the other page at their default sizes.
We will also sort out whether the second page should be printed in portrait or landscape orientation.
Here's the code to do that:
Search WWH ::




Custom Search