Side of Software

 

 

Home

 

Contact Us

 

 

 Products

 

Dated Collections

 

Marker Bar

 

Persistence

 

Print Preview

 

FAQs

Tutorial

 

API (javadocs)

 

Reports

 

Wizards

Print Preview Tutorial

Table of Contents

Introduction

Page Content

Using a Standard Toolbar

Building Custom Toolbars

Working with JPrintPreviewPane

Customizing the Look and Feel

Example

Introduction

Most user-friendly applications have a print preview screen that allows the user to preview pages before printing them. On the print preview screen, users typically can zoom in and out on the pages, change the arrangement of pages, change the page format, and print the pages. Although each application may have a slightly different print preview screen, the basic functionality is the same.

 

The core Java libraries do not provide high-level support for print preview. As a result, developers either implement their own print preview screens or disregard it entirely. By providing the basic print preview functionality, the Print Preview Library makes it easy to add print preview to an application. The library offers a general-purpose Swing component that previews pages, four layout managers that arrange pages on the screen, and a support class that helps build a print preview toolbar.

 

Before you start using this library, you should download and include on your classpath the jar file of the Java Look and Feel Graphics Repository. It is available free-of-charge here. Without this resource, your print preview toolbar will not have any icons or cursors.

Page Content

The Print Preview Library does not deal with the page content. Therefore, it is not a report generation tool. The print preview pane relies on a java.awt.Pageable object to render the contents of each page. It is the developer’s responsibility to provide an appropriate Pageable object.

 

That said, the library does provide a utility class, ComponentPageable, that simplifies the common case of previewing and printing a Swing component. With this class, you can easily convert any component—a JTable, JTree, or JPanel, for instance—into a Pageable object.

 

  JComponent componentToPreview = ...  // application specific
  Pageable pageable = new ComponentPageable( componentToPreview );

 

Also, Side of Software offers the Report Library, a separate reporting framework that creates Pageable objects from sophisticated reports.

 

Once you have your Pageable object, you are ready to make use of the library’s features.

Using a Standard Toolbar

The library offers two "standard" toolbars: Navigation and Zoom. These toolbars, which are commonly found across existing applications, can be created with a single call to a factory method.

The Navigation Toolbar

The navigation toolbar allows the user to print the pages, change the page format, step through the pages one at a time, and close print preview. On a Windows machine, the toolbar may resemble:

 

 

To create a print preview pane with an accompanying navigation toolbar, invoke one of the static createNavigationPanel factory methods found in PrintPreviewSupport:

 

  static JPanel createNavigationPanel(Pageable pageable,
                                      boolean showPrintDialog,
                                      Action closeAction,
                                      boolean largeIcons)
 
  static JPanel createNavigationPanel(PageableFactory pageableFactory,
                                      boolean showPrintDialog,
                                      Action closeAction,
                                      boolean largeIcons)
 

The methods differ only in the first parameter. The first method takes the preview pages (pageable) and does not allow the user to change the page format. The second method, on the other hand, takes a PageableFactory that can generate the preview pages on demand, thereby supporting changes in page format. Generally, you should use the second method only if all pages follow the same page format.

 

The remaining three parameters are treated as follows:

 

showPrintDialog

true if the print button should show the print dialog before printing the pages; false if the print button should print all pages automatically.

closeAction

The action to perform when the close button is clicked.

largeIcons

Whether or not the toolbar should use large icons.

 

The following code snippet creates a print preview pane with a navigation toolbar.

 

  // create an object that will render the contents 
  // of each page (application specific)
  Pageable pageable = ... 
 
  // create an action that will close 
  // print preview (application specific)
  Action closeAction = ...
 
  // create the print preview panel with
  // a navigation toolbar
  JPanel printPreviewPanel = PrintPreviewSupport.createNavigationPane( 
    pageable, false, closeAction, false );
 
  // add the panel to your application
  // (application specific)
  JComponent contentPane = ...
  contentPane.add( printPreviewPanel );

 

The Zoom Toolbar

The zoom toolbar allows the user to print the pages, change the page format, zoom in and out on the pages, change the arrangement of pages, and close print preview. There are four different zoom behaviors:

 

Zoom Behavior

Description

ZOOM

The user is always in zoom mode. Left-clicking a preview page will zoom in on the page, while right-clicking a preview page will zoom out on the page. The zoomed view will be centered as close as possible to the point of click.

ZOOM_TOGGLE

The user can toggle between zoom mode and selection mode. In zoom mode, the user can zoom in and out; in selection mode, the user can select pages.

ZOOM_IN_OUT

The user is always in selection mode but can zoom in and out by clicking the appropriate toolbar buttons. The zoomed view is centered on the page that is closest to the center of the screen.

ZOOM_IN_OUT_TOGGLE

The user can toggle between zoom-in mode and zoom-out mode. In zoom-in mode, all mouse clicks zoom in on a page. In zoom-out mode, all mouse clicks zoom out. The zoomed view will be centered as close as possible to the point of click.

 

On a Windows machine, the toolbar for each of these behaviors may look like:

 

 

 

 

 

To create a panel with a print preview pane and a navigation toolbar, invoke one of the static createZoomPanel factory methods:

 

  static JPanel createZoomPanel(Pageable pageable,
                                boolean showPrintDialog,
                                int zoomFlavor,
                                Action closeAction,
                                boolean largeIcons)
 
  static JPanel createZoomPanel(PageableFactory pageableFactory,
                                boolean showPrintDialog,
                                int zoomFlavor,
                                Action closeAction,
                                boolean largeIcons)
 

Again, the methods differ only in the first parameter. The second method includes a page setup button on the toolbar. The printFlavor, closeAction, and largeIcons parameters follow the same guidelines as above.

                                                                                                                               

The following code snippet creates a print preview pane with a zoom toolbar.

 

  // create an object that will render the contents 
  // of each page (application specific)
  Pageable pageable = ... 
 
  // create an action that will close 
  // print preview (application specific)
  Action closeAction = ...
 
  // create the print preview panel with
  // a zoom toolbar
  JPanel printPreviewPanel = PrintPreviewSupport.createZoomPane( 
    pageable, false, PrintPreviewSupport.ZOOM_IN_OUT_TOGGLE,
    closeAction, false );
 
  // add the panel to your application
  // (application specific)
  JComponent contentPane = ...
  contentPane.add( printPreviewPanel );

 

Building Custom Toolbars

If you prefer not to use the standard toolbars, you can build your own toolbars with the help of an instance of PrintPreviewSupport. PrintPreviewSupport offers many methods to create common toolbar components:

 

Toolbar Component

Description

Print Button

Displays the platform-specific print dialog and prints the pages if the user accepts the print dialog.

Print All Button

Prints all pages without displaying the print dialog.

Page Setup Button

Displays the page setup dialog and creates a new Pageable instance if a valid PageableFactory is provided.

Zoom In Button

Zooms in at the center of the screen.

Zoom Out Button

Zooms out at the center of the screen.

Zoom In Toggle Button

Toggles between zoom-in mode and selection mode.

Zoom Out Toggle Button

Toggles between zoom-out mode and selection mode.

Zoom Toggle Button

Toggles between zoom mode and selection mode.

Next Page Button

Displays the next print preview page.

Previous Page Button

Displays the previous print preview page.

First Page Button

Displays the first print preview page.

Last Page Button

Displays the last print preview page.

Page Field

Reflects the current print preview page being shown. If the user types a value, the print preview pane displays the desired page.

Zoom Combobox

Switches among page layouts. If the user types a value, the appropriate page layout is created and installed in the print preview pane. For Locale.US, acceptable values include “n%” (zoom layout), “n x m” (matrix layout), “Fit All,” “Fit Page Width,” “Fit Page Height,” “One Page,” and “Two Page.”

Close Button

Closes print preview.

 

It supports only one instance of each of these components. Thus, it is not possible (through PrintPreviewSupport) to have two print buttons on the toolbar.

 

For many of the above components, you will find the following methods:

 

  public <Component> getXxxComponent();
  public Action getXxxAction();
  public String getXxxText();
  public Icon getXxxIcon();
  public String getXxxToolTip();
  public int getXxxMnemonic();

 

The methods return a component, action, name, icon, tool tip, and mnemonic, respectively, appropriate for the task Xxx. Invoke the method that serves your needs. For example, if you wish to add a previous page button to your toolbar, invoke getPreviousPageButton. If you wish to create your own component yet use the text and description associated with the previous page action, invoke getPreviousPageText and getPreviousPageToolTip.

Custom Toolbar Example

Suppose in your application you want to provide a minimal print preview pane that allows the user to print all pages, select a zoom layout, and display help information. PrintPreviewSupport does not provide a factory method to create such a toolbar; however, it does provide the functionality to print all pages and select a zoom layout. Your application can take advantage of the built-in functionality:

 

  // create a print preview pane component
  Pageable pageable = ...
  JPrintPreviewPane printPreviewPane = new JPrintPreviewPane( 
    pageable );
 
  // create the print preview toolbar
  JToolBar toolBar = new JToolBar();
 
  // enlist some help in creating the toolbar
  PrintPreviewSupport support = new PrintPreviewSupport( 
    printPreviewPane, true );
 
  // use the built-in print button
  JButton printAllButton = support.getPrintAllButton();
  printAllButton.setText( "" );     // show no text
  printAllButton.setBorder( null ); // show no border
 
  // use the built-in zoom combobox
  JComboBox zoomCombo = support.getZoomComboBox( false, false );
 
  // create our own help button (application specific)
  JButton helpButton = ...
 
  // add these components to the toolbar
  toolBar.add( printAllButton );
  toolBar.addSeparator();
  toolBar.add( zoomCombo );
  toolBar.addSeparator();
  toolBar.add( helpButton );
 
  // place the print preview pane in a scroll pane
  JScrollPane scrollPane = new JScrollPane( printPreviewPane );
 
  // add the scroll pane and toolbar to a panel
  JPanel panel = new JPanel( new BorderLayout() );
  panel.add( scrollPane, BorderLayout.CENTER );
  panel.add( toolBar, BorderLayout.PAGE_START );
 

The above code creates the following toolbar.

 

Subclassing PrintPreviewSupport

You can subclass PrintPreviewSupport in order to make small changes to the built-in behavior. For example, suppose you are happy with the built-in navigation pane but wish the print button read “Print Dialog...” instead of “Print...” You can create a subclass of PrintPreviewSupport and override getPrintText, as follows:

 

  class CustomPrintPreviewSupport extends PrintPreviewSupport
  {
    public CustomPrintPreviewSupport( JPrintPreviewPane printPreviewPane, 
                                      boolean largeIcons )
    {
      super( printPreviewPane, largeIcons );
    }
  
    public String getPrintText()
    {
      return "Print Dialog...";
    }
  }
 

Working with JPrintPreviewPane

JPrintPreviewPane provides numerous methods to allow you to manipulate it. You can change the page layout, zoom in and out, switch the user mode, and select pages.

Page Layouts

The print preview pane must decide how to arrange the pages. JPrintPreviewPane accomplishes this by installing page components as children and asking the layout manager to arrange the children. This library provides four types of page layout, as described in the following table.

 

Page Layout

Description

ZoomLayout

Scales pages a prescribed amount.

MatrixLayout

Arranges pages into x rows and y columns per screen, where x and y can be any positive integer.

FitAllLayout

Fits all pages on the screen.

FitLayout

Fits either the horizontal or the vertical axis of the largest page on the screen.

 

These four page layouts implement java.awt.LayoutManager and are accessed using the methods defined in superclass java.awt.Container:

 

  public void setLayout( LayoutManager layout );
  public LayoutManager getLayout();

 

You can listen for changes to the layout manager by registering a property change listener on the key LAYOUT_PROPERTY.

 

You can customize the arrangement of pages by defining your own java.awt.LayoutManager. If your custom layout scheme dictates how the print preview pane should scroll, then it should implement the interface ScrollableLayoutManager. If your custom layout scheme works by scaling the preview pages, then it should implement the interface ScalingLayoutManager.

Zooming

JPrintPreviewPane actually achieves zooming by changing the layout manager to an appropriate ZoomLayout instance. It provides the following convenience methods:

 

  public double getScale();
  public boolean zoom( double scale );
  public boolean zoom( double scale, Point point );
  public boolean zoomIn();
  public void zoomIn( int pageIndex );
  public boolean zoomIn( Point point );
  public boolean zoomOut();
  public void zoomOut( int pageIndex );
  public boolean zoomOut( Point point );
 

When a java.awt.Point argument is provided in one of the above methods, the print preview pane attempts to zoom at the specified point. The zoomed view tries to put at its center the same relative position of the page at that point. When a page index is provided, the print preview pane zooms at the center of the specified page. When neither a point nor a page index is provided, the component zooms at the point on a page nearest the center of the visible region.

 

When there is a change in zoom, JPrintPreviewPane sends a PropertyChangeEvent for the key SCALE_PROPERTY.

 

To determine how far the pane should zoom, it asks an instance of ZoomFunction, which is defined as follows:

 

  public interface ZoomFunction
  {
    public double zoomIn(double scale);
    public double zoomOut(double scale);
  }

 

Given the current scale, these methods return the next scale for zooming either in or out. By returning the same value as the parameter, ZoomFunction essentially disallows the zoom. The default behavior allows zooming out to 1% and unlimited zooming in. Each step (in or out) is 25% of the current zoom factor.

 

You can customize the amount of zooming the print preview pane provides by installing a custom implementation of ZoomFunction and invoking

 

  public void setZoomFunction( ZoomFunction zoomFunction );

 

The custom implementation may either implement ZoomFunction directly or be a customized instance of DefaultZoomFunction.

Modes

JPrintPreviewPane can be in exactly one of four user modes:

 

Mode

Description

SELECTION_MODE

The user can select one or more pages.

ZOOM_MODE

The user can zoom in and out on the pages by left-clicking and right-clicking the mouse, respectively.

ZOOM_IN_MODE

The user can zoom in on the pages by clicking the mouse.

ZOOM_OUT_MODE

The user can zoom out on the pages by clicking the mouse.

 

The following methods set and retrieve the mode:

 

  public int getMode();
  public void setMode(int mode);

 

You can listen for changes to the mode by registering a property change listener on the key MODE_PROPERTY.

Page Selection

When JPrintPreviewPane is in selection mode, one or more pages can be selected. Each JPrintPreviewPane instance has an underlying selection model. The following methods deal with page selection:

 

  public ListSelectionModel getPageSelectionModel();
  public boolean isPageSelected( int pageIndex );
  public void setPageSelectionModel( ListSelectionModel selectionModel );
  public boolean getPageSelectionAllowed();
  public int getSelectedPageIndex();
  public void setPageSelectionAllowed( boolean pageSelectionAllowed );

 

You can listen for changes to the selection by registering a ListSelectionListener with the selection model.

Page Numbering

When page numbering is turned on, the print preview pane displays a page number for each page. You can turn page numbering on and off with

 

  public void setPageNumbersAreShown( boolean pageNumbersAreShown );
 

The page number is rendered using an instance of PageNumberRenderer. By default, it is rendered as a numeral centered beneath the page. You can change the way page numbers are rendered with

 

  public void setPageNumberRenderer( PageNumberRenderer pageNumberRenderer );
 

Page number renderers must implement a method that returns a component ready to render the page number:

 
  public interface PageNumberRenderer
  {
    public Component getPageNumberRendererComponent( 
      JPrintPreviewPane printPreviewPane, 
      int pageNumber, 
      boolean isSelected, 
      boolean pageHasFocus );
  }
 

The library provides one implementation of PageNumberRenderer: DefaultPageNumberRenderer. This implementation uses a shared JLabel component to render the page numbers. Developers can subclass DefaultPageNumberRenderer to customize the look of the label. In anticipation of customization, DefaultPageNumberRenderer invokes two protected methods when initializing the label: pageNumberToString and prepareLabel. If you wish to change the displayed text, override pageNumberToString. If you wish to change the appearance of the label (for example, the color or font), override prepareLabel.

 

Here is a an example of a custom page number renderer that overrides pageNumberToString to display the word “Page” before each page number.

 

  class CustomPageNumberRenderer extends DefaultPageNumberRenderer
  {
    protected String pageNumberToString( int pageNumber )
    {
      return "Page " + pageNumber;
    }
  }

Custom Preview Pages

You can change the appearance of each previewed page. By default, the print preview pane creates a JPrintPreviewPage component for each page being previewed. Each JPrintPreviewPage gets rendered as a rectangle with a border and shadow atop a page number. You can substitute a custom java.awt.Component class for JPrintPreviewPage. To do this, subclass JPrintPreviewPane and override createPageComponent. Your custom component should implement Scaleable if it does not scale uniformly.

Customizing the Look and Feel

You can further customize your print preview pane by defining look-and-feel properties. At application start-up, define the properties you wish to change with the call

 

  UIManager.put( propertyKey, propertyValue );

 

where propertyKey specifies the property and propertyValue is the desired value. The type of propertyValue depends on the property key. The key should be one of the following keys:

 

Property Key

Value Type

Description

 

BasicPrintPreviewPaneUI:

 

BACKGROUND_KEY

java.awt.Color

The print preview pane’s background color. The space between pages is this color.

SELECTION_BACKGROUND_KEY

java.awt.Color

The print preview pane’s selection background color. A page or page number renderer may use this value when rendering itself.

SELECTION_FOREGROUND_KEY

java.awt.Color

The print preview pane’s selection foreground color. A page or page number renderer may use this value when rendering itself.

 

BasicPrintPreviewPageUI:

 

BORDER_THICKNESS_KEY

java.lang.Integer

The print preview page’s border thickness. The value indicates the width of the rectangle surrounding the page content.

SHADOW_THICKNESS_KEY

java.lang.Integer

The print preview page’s shadow thickness. The value indicates the shift of the shadow drawn beneath the page.

BACKGROUND_KEY

java.awt.Color

The print preview page’s background color. The color of the page is this color.

FOREGROUND_KEY

java.awt.Color

The print preview page’s foreground color. The page border is rendered in this color.

SHADOW_COLOR_KEY

java.awt.Color

The print preview page’s shadow color. The page shadow is rendered in this color.

MARGIN_COLOR_KEY

java.awt.Color

The print preview page’s margin color. The page margin is rendered in this color.

MARGIN_STROKE_KEY

java.awt.Stroke

The print preview page’s margin stroke. The page margin is drawn with this stroke.

CACHING_POLICY_KEY

java.lang.Object

The print preview page’s caching policy. If the value is set to NEVER_CACHE_VALUE (the default), the print method of the client's printable object is invoked each time the print preview page is repainted. If the value is set to ALWAYS_CACHE_VALUE, the print method is invoked once (at each zoom level), and the image is cached for use during repainting. Last, if the value is MEMORY_SENSITIVE_CACHE_VALUE, images are cached, but the cache may be flushed if memory is in demand.

 

Example

The example PrintPreviewDemo demonstrates the flexibility of print preview panes.  It displays pages of text beneath a custom tool bar and allows the user to add and remove pages, change the look and feel of the pages, and zoom in and out. In this application, you can find examples of how to

 

  • Create a print preview pane
  • Build a custom print preview toolbar with the help of PrintPreviewSupport
  • Change the look and feel of the print preview pane
  • Change the look and feel of the print preview pages
  • Listen for a property change on a print preview pane
  • Switch the print preview pane’s mode
  • Create a custom page number renderer
  • Alter the page selection model

 

You can run this sample application on the library’s homepage.

 

 

Home  |  Contact Us  |  Privacy Policy

 

Copyright © 2014 Side of Software, a branch of Natavision. All rights reserved.