COMPONENT JAVAJava 2 Printing

COMPONENT JAVA
Java 2 Printing

Matthew Robinson and Pavel Vorobiev

Listing 1. A JLabel subclass that can be printed as a matrix of pages.


import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.print.*;

import java.util.*;

import javax.swing.*;
public class PrintableLabel extends JLabel implements Printable
{
  // Initial page count.
  // This is recalculated during printing.
  protected int m_maxNumPage = 1;

  protected Image m_image = null;  
  
  public PrintableLabel(ImageIcon image) {
    super(image);
    m_image = image.getImage();    
  }

  public int print(Graphics pg, 
    PageFormat pageFormat, int pageIndex) 
    throws PrinterException 
  {
    if (pageIndex >= m_maxNumPage || m_image == null)
      return NO_SUCH_PAGE;

    pg.translate((int)pageFormat.getImageableX(), 
      (int)pageFormat.getImageableY());
    int wPage = (int)pageFormat.getImageableWidth();
    int hPage = (int)pageFormat.getImageableHeight();

    int w = m_image.getWidth(this);
    int h = m_image.getHeight(this);
    if (w == 0 || h == 0)
      return NO_SUCH_PAGE;
    int nCol = Math.max((int)Math.ceil((double)w/wPage), 1);
    int nRow = Math.max((int)Math.ceil((double)h/hPage), 1);
    m_maxNumPage = nCol*nRow;
    
    int iCol = pageIndex % nCol;
    int iRow = pageIndex / nCol;
    int x = iCol*wPage;
    int y = iRow*hPage;
    int wImage = Math.min(wPage, w-x);
    int hImage = Math.min(hPage, h-y);

    pg.drawImage(m_image, 0, 0, wImage, hImage, 
      x, y, x+wImage, y+hImage, this);
    
    System.gc();
    
    return PAGE_EXISTS;
  }

  public static void main(String[] args) {
    JFrame myframe = new JFrame("Printable Demo");
    myframe.setSize(400,400);
    
    PrintableLabel pl = new PrintableLabel(
       new ImageIcon("shuttle.jpg"));
    
    myframe.getContentPane().add(new JScrollPane(pl));
    myframe.setVisible(true);
    
    PrintPreview pp = new PrintPreview(pl);
  }
}