Java Reference
In-Depth Information
Example 12−4: PrintableDocument.java (continued)
this.printHeight = format.getImageableHeight()/scalefactor;
double paperWidth = format.getWidth()/scalefactor;
// Get the document and its root Element from the text component
Document document = textComponent.getDocument();
Element rootElement = document.getDefaultRootElement();
// Get the EditorKit and its ViewFactory from the text component
EditorKit editorKit =textComponent.getUI().getEditorKit(textComponent);
ViewFactory viewFactory = editorKit.getViewFactory();
// Use the ViewFactory to create a root View object for the document
// This is the object we'll print.
root = viewFactory.create(rootElement);
// The Swing text architecture requires us to call setParent() on
// our root View before we use it for anything. In order to do this,
// we need a View object that can serve as the parent. We use a
// custom implementation defined below.
root.setParent(new ParentView(root, viewFactory, textComponent));
// Tell the view how wide the page is; it has to format itself
// to fit within this width. The height doesn't really matter here
root.setSize((float)printWidth, (float)printHeight);
// Now that the view has formatted itself for the specified width,
// Ask it how tall it is.
double documentHeight = root.getPreferredSpan(View.Y_AXIS);
// Set up the rectangle that tells the view where to draw itself
// We'll use it in other methods of this class.
drawRect = new Rectangle(0, 0, (int)printWidth, (int)documentHeight);
// Now if the document is taller than one page, we have to
// figure out where the page breaks are.
if (documentHeight > printHeight) paginate(root, drawRect);
// Once we've broken it into pages, figure out how many pages.
numPages = pageLengths.size() + 1;
}
// This is the starting offset of the page we're currently working on
double pageStart = 0;
/**
* This method loops through the children of the specified view,
* recursing as necessary, and inserts pages breaks when needed.
* It makes a rudimentary attempt to avoid "widows" and "orphans".
**/
protected void paginate(View v, Rectangle2D allocation) {
// Figure out how tall this view is, and tell it to allocate
// that space among its children
double myheight = v.getPreferredSpan(View.Y_AXIS);
v.setSize((float)printWidth, (float)myheight);
// Now loop through each of the children
int numkids = v.getViewCount();
for(int i = 0; i < numkids; i++) {
View kid = v.getView(i); // this is the child we're working with
Search WWH ::




Custom Search