edu.northwestern.at.utils.swing.printing
Class PrintableComponent

java.lang.Object
  extended by java.awt.Component
      extended by edu.northwestern.at.utils.swing.printing.PrintableComponent
All Implemented Interfaces:
PrintProgress, java.awt.image.ImageObserver, java.awt.MenuContainer, java.awt.print.Pageable, java.awt.print.Printable, java.io.Serializable
Direct Known Subclasses:
PrintJTable, PrintJTextPane

public class PrintableComponent
extends java.awt.Component
implements java.awt.print.Pageable, PrintProgress

Base class for printing contents of a Component descendant.

This class provides basic machinery for creating a printing class for a specified type of component. Printing will be Pageable and allow for a progress display. Optional page headers and footers can be printed on each page as well. Any type of component descending from the AWT type component can be printed as long as the component knows how to print itself.

See Also:
Serialized Form

Nested Class Summary
protected  class PrintableComponent.PageState
          Class holding information about each printed page.
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
protected  double breakCheckPercentage
          Percentage of page height to scan for nice page break point.
protected  java.awt.Component component
          Compoment whose contents are to be printed.
protected  PrintHeaderFooter headerAndFooter
          The PrintHeaderFooter to hold the header and footer.
protected  int pageCount
          The number of pages to be printed.
protected  java.awt.print.PageFormat pageFormat
          Printer page format.
protected  java.awt.image.BufferedImage pageImage
          Holds printed page page image.
protected  PrintableComponent.PageState pageState
          Current page state.
protected  java.util.HashMap pageStateMap
          Holds page state for each printed page.
protected  java.awt.print.PrinterJob printerJob
          Printer job for printing the pages.
protected  int printerPageHeight
          Printer page height specified by printer job.
protected  int printerPageWidth
          Printer page width specified by printer job.
protected  PrintProgressDialog printProgress
          Print progress dialog.
protected  boolean printProgressAllowed
          True if print progress display allowed.
protected  double scaleFactor
          Scale factor by which to reduce output to fit printer page.
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.print.Pageable
UNKNOWN_NUMBER_OF_PAGES
 
Fields inherited from interface java.awt.print.Printable
NO_SUCH_PAGE, PAGE_EXISTS
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
PrintableComponent(java.awt.Component component)
          Create PrintableComponent object.
PrintableComponent(java.awt.Component component, java.awt.print.PageFormat pageFormat)
          Create PrintableComponent object.
PrintableComponent(java.awt.Component component, java.awt.print.PageFormat pageFormat, PrintHeaderFooter headerAndFooter)
          Create PrintableComponent object.
 
Method Summary
 int calculatePageCount()
          Calculate count of printed pages.
 void closeProgress()
          Close print progress dialog.
 void doPrintContents()
          Print the contents of the JComponent.
 int getFooterSize(java.awt.Graphics pg)
          Get footer size needed.
 int getHeaderSize(java.awt.Graphics pg)
          Get header size needed.
 int getNumberOfPages()
          Return number of pages to print.
 java.awt.print.PageFormat getPageFormat(int pageIndex)
          Return printer page format for a given page index.
 java.awt.print.Printable getPrintable(int pageIndex)
          Return printable for given page index.
protected  int getSliceLength(double percentage, double scaleFactor)
          Get slice length with nice place to split a page image.
 int print(java.awt.Graphics pg, java.awt.print.PageFormat pageFormat, int pageIndex)
          Print one page of component.
 void printContents()
          Print the contents of the JComponent in a separate thread.
 void printHeaderAndFooter(java.awt.Graphics2D pg2D)
          Print the header and footer.
protected  void printPage(java.awt.Graphics2D pg2D, int pageOffset, int pageLength, int headerSize, double scaleFactor, boolean addMargins)
          Paint page into specified graphics content.
 void setBreakCheckPercentage(double breakCheckPercentage)
          Set break check percentage.
 void setPageFormat(java.awt.print.PageFormat pageFormat)
          Set page format.
 void setPrinterJob(java.awt.print.PrinterJob printerJob)
          Set printer job.
 void setProgress(boolean onOff)
          Enable or disable print progress.
 void updateProgress(int pagesPrinted)
          Update printed pages status display with number of pages printed.
 void validateLayout()
          Validate component layout.
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, addNotify, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, deliverEvent, disable, disableEvents, dispatchEvent, doLayout, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getAccessibleContext, getAlignmentX, getAlignmentY, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentAt, getComponentAt, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeys, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMaximumSize, getMinimumSize, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, invalidate, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusCycleRoot, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, layout, list, list, list, list, list, locate, location, lostFocus, minimumSize, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paint, paintAll, paramString, postEvent, preferredSize, prepareImage, prepareImage, print, printAll, processComponentEvent, processEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removeNotify, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeys, setFocusTraversalKeysEnabled, setFont, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusBackward, transferFocusUpCycle, update, validate
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

component

protected java.awt.Component component
Compoment whose contents are to be printed.


pageFormat

protected java.awt.print.PageFormat pageFormat
Printer page format.


headerAndFooter

protected PrintHeaderFooter headerAndFooter
The PrintHeaderFooter to hold the header and footer.


pageCount

protected int pageCount
The number of pages to be printed. Calculated here.


printProgress

protected PrintProgressDialog printProgress
Print progress dialog.


printProgressAllowed

protected boolean printProgressAllowed
True if print progress display allowed.


printerJob

protected java.awt.print.PrinterJob printerJob
Printer job for printing the pages.


printerPageWidth

protected int printerPageWidth
Printer page width specified by printer job.


printerPageHeight

protected int printerPageHeight
Printer page height specified by printer job.


pageImage

protected java.awt.image.BufferedImage pageImage
Holds printed page page image.


pageState

protected PrintableComponent.PageState pageState
Current page state.


pageStateMap

protected java.util.HashMap pageStateMap
Holds page state for each printed page.


breakCheckPercentage

protected double breakCheckPercentage
Percentage of page height to scan for nice page break point.


scaleFactor

protected double scaleFactor
Scale factor by which to reduce output to fit printer page.

Constructor Detail

PrintableComponent

public PrintableComponent(java.awt.Component component,
                          java.awt.print.PageFormat pageFormat,
                          PrintHeaderFooter headerAndFooter)
Create PrintableComponent object.

Parameters:
component - Component to print.
pageFormat - The printer page format.
headerAndFooter - The header and footer for this page.

PrintableComponent

public PrintableComponent(java.awt.Component component,
                          java.awt.print.PageFormat pageFormat)
Create PrintableComponent object.

Parameters:
component - The component whose contents are to be printed.
pageFormat - The printer page format.

No header, footer, or line numbers are printed.


PrintableComponent

public PrintableComponent(java.awt.Component component)
Create PrintableComponent object.

Parameters:
component - The component whose contents are to be printed.

No header, footer, or line numbers are printed.

Method Detail

validateLayout

public void validateLayout()
Validate component layout.


printContents

public void printContents()
Print the contents of the JComponent in a separate thread.

We need to print the component contents in a separate thread so that the print progress dialog will work.


doPrintContents

public void doPrintContents()
Print the contents of the JComponent.

You can call this method instead of printContents() if you are setting up your own printing thread.


getHeaderSize

public int getHeaderSize(java.awt.Graphics pg)
Get header size needed.

Parameters:
pg - The graphics context in which to print the header.
Returns:
Vertical size of header.

Normally the header size is just the size of the header, if any, plus an extra blank line (in the same font size as the header). For some components the header space may be larger. For example, for a JTable, the header space is increased by the amount of space required to print the table column headers.


getFooterSize

public int getFooterSize(java.awt.Graphics pg)
Get footer size needed.

Parameters:
pg - The graphics context in which to print the header.
Returns:
Vertical size of footer.

Normally the footer space needed is just the size of the footer, if any, plus an extra blank line (in the same font size as the header).


printHeaderAndFooter

public void printHeaderAndFooter(java.awt.Graphics2D pg2D)
Print the header and footer.

Parameters:
pg2D - The graphics context into which to print the header and footer, if any.

print

public int print(java.awt.Graphics pg,
                 java.awt.print.PageFormat pageFormat,
                 int pageIndex)
Print one page of component.

Specified by:
print in interface java.awt.print.Printable
Parameters:
pg - Graphics context into which to draw page image.
pageFormat - Contains information about page size and paper orientation.
pageIndex - Which page to print (starts at zero).
Returns:
PAGE_EXISTS if page exists NO_SUCH_PAGE if page does not exist

A printer page size chunk of the component is printed for the specified page index.


calculatePageCount

public int calculatePageCount()
Calculate count of printed pages.

Returns:
Count of pages to print.

getNumberOfPages

public int getNumberOfPages()
Return number of pages to print.

Specified by:
getNumberOfPages in interface java.awt.print.Pageable
Returns:
Count of pages to print.

printPage

protected void printPage(java.awt.Graphics2D pg2D,
                         int pageOffset,
                         int pageLength,
                         int headerSize,
                         double scaleFactor,
                         boolean addMargins)
Paint page into specified graphics content.

Parameters:
pg2D - Graphics buffer into which to print component slice.
pageOffset - Component offset at which to start printing.
pageLength - Length of component slice to print.
headerSize - Size of header.
scaleFactor - Scale factor for printing slice.
addMargins - True to account for printer page margins.

setBreakCheckPercentage

public void setBreakCheckPercentage(double breakCheckPercentage)
Set break check percentage.

Parameters:
breakCheckPercentage - Percentage of page height to check for a clean page break.

A break check value of 0.20 (20%) work well and is the default. A new break check value must be >= 0.0 and < 1.0 .


getSliceLength

protected int getSliceLength(double percentage,
                             double scaleFactor)
Get slice length with nice place to split a page image.

Parameters:
percentage - How far up page to look as a percentage of printer page height.
scaleFactor - If we're scaling the output.

We apply the following heuristics to find a "nice" place to split the printed image when mapping the image buffer to a series of pages.

  1. Starting with the last line of pixels in the slice, we move back in the image slice looking for a blank line -- e.g., one with all pixels set to the background color. While doing so we keep a tally of the number of pixels which are not equal to the background color (e.g., are set) in each line. We stop when we find a "blank" line or we have moved up the specified percent of the printer page size.
  2. If we found a blank line, split the component image at that line.
  3. If we did not find a blank line, select the line with the least number of set pixels closest to the bottom of the original slice.

getPageFormat

public java.awt.print.PageFormat getPageFormat(int pageIndex)
Return printer page format for a given page index.

Specified by:
getPageFormat in interface java.awt.print.Pageable
Parameters:
pageIndex - Index of page.
Returns:
PageFormat for specified page.

getPrintable

public java.awt.print.Printable getPrintable(int pageIndex)
Return printable for given page index.

Specified by:
getPrintable in interface java.awt.print.Pageable
Parameters:
pageIndex - Index of page.
Returns:
Printable for specified page.

setProgress

public void setProgress(boolean onOff)
Enable or disable print progress.

Specified by:
setProgress in interface PrintProgress
Parameters:
onOff - True to enable print progress, false to disable.

updateProgress

public void updateProgress(int pagesPrinted)
Update printed pages status display with number of pages printed.

Specified by:
updateProgress in interface PrintProgress
Parameters:
pagesPrinted - Number of pages printed so far.

closeProgress

public void closeProgress()
Close print progress dialog.

Specified by:
closeProgress in interface PrintProgress

setPrinterJob

public void setPrinterJob(java.awt.print.PrinterJob printerJob)
Set printer job.

Specified by:
setPrinterJob in interface PrintProgress
Parameters:
printerJob - The printer job used for printing.

setPageFormat

public void setPageFormat(java.awt.print.PageFormat pageFormat)
Set page format.

Specified by:
setPageFormat in interface PrintProgress
Parameters:
pageFormat - The page format used for printing.