0N/A/*
2362N/A * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage javax.swing;
0N/A
0N/Aimport javax.swing.table.*;
0N/Aimport java.awt.*;
0N/Aimport java.awt.print.*;
0N/Aimport java.awt.geom.*;
0N/Aimport java.text.MessageFormat;
0N/A
0N/A/**
0N/A * An implementation of <code>Printable</code> for printing
0N/A * <code>JTable</code>s.
0N/A * <p>
0N/A * This implementation spreads table rows naturally in sequence
0N/A * across multiple pages, fitting as many rows as possible per page.
0N/A * The distribution of columns, on the other hand, is controlled by a
0N/A * printing mode parameter passed to the constructor. When
0N/A * <code>JTable.PrintMode.NORMAL</code> is used, the implementation
0N/A * handles columns in a similar manner to how it handles rows, spreading them
0N/A * across multiple pages (in an order consistent with the table's
0N/A * <code>ComponentOrientation</code>).
0N/A * When <code>JTable.PrintMode.FIT_WIDTH</code> is given, the implementation
0N/A * scales the output smaller if necessary, to ensure that all columns fit on
0N/A * the page. (Note that width and height are scaled equally, ensuring that the
0N/A * aspect ratio remains the same).
0N/A * <p>
0N/A * The portion of table printed on each page is headed by the
0N/A * appropriate section of the table's <code>JTableHeader</code>.
0N/A * <p>
0N/A * Header and footer text can be added to the output by providing
0N/A * <code>MessageFormat</code> instances to the constructor. The
0N/A * printing code requests Strings from the formats by calling
0N/A * their <code>format</code> method with a single parameter:
0N/A * an <code>Object</code> array containing a single element of type
0N/A * <code>Integer</code>, representing the current page number.
0N/A * <p>
0N/A * There are certain circumstances where this <code>Printable</code>
0N/A * cannot fit items appropriately, resulting in clipped output.
0N/A * These are:
0N/A * <ul>
0N/A * <li>In any mode, when the header or footer text is too wide to
0N/A * fit completely in the printable area. The implementation
0N/A * prints as much of the text as possible starting from the beginning,
0N/A * as determined by the table's <code>ComponentOrientation</code>.
0N/A * <li>In any mode, when a row is too tall to fit in the
0N/A * printable area. The upper most portion of the row
0N/A * is printed and no lower border is shown.
0N/A * <li>In <code>JTable.PrintMode.NORMAL</code> when a column
0N/A * is too wide to fit in the printable area. The center of the
0N/A * column is printed and no left and right borders are shown.
0N/A * </ul>
0N/A * <p>
0N/A * It is entirely valid for a developer to wrap this <code>Printable</code>
0N/A * inside another in order to create complex reports and documents. They may
0N/A * even request that different pages be rendered into different sized
0N/A * printable areas. The implementation was designed to handle this by
0N/A * performing most of its calculations on the fly. However, providing different
0N/A * sizes works best when <code>JTable.PrintMode.FIT_WIDTH</code> is used, or
0N/A * when only the printable width is changed between pages. This is because when
0N/A * it is printing a set of rows in <code>JTable.PrintMode.NORMAL</code> and the
0N/A * implementation determines a need to distribute columns across pages,
0N/A * it assumes that all of those rows will fit on each subsequent page needed
0N/A * to fit the columns.
0N/A * <p>
0N/A * It is the responsibility of the developer to ensure that the table is not
0N/A * modified in any way after this <code>Printable</code> is created (invalid
0N/A * modifications include changes in: size, renderers, or underlying data).
0N/A * The behavior of this <code>Printable</code> is undefined if the table is
0N/A * changed at any time after creation.
0N/A *
0N/A * @author Shannon Hickey
0N/A */
0N/Aclass TablePrintable implements Printable {
0N/A
0N/A /** The table to print. */
0N/A private JTable table;
0N/A
0N/A /** For quick reference to the table's header. */
0N/A private JTableHeader header;
0N/A
0N/A /** For quick reference to the table's column model. */
0N/A private TableColumnModel colModel;
0N/A
0N/A /** To save multiple calculations of total column width. */
0N/A private int totalColWidth;
0N/A
0N/A /** The printing mode of this printable. */
0N/A private JTable.PrintMode printMode;
0N/A
0N/A /** Provides the header text for the table. */
0N/A private MessageFormat headerFormat;
0N/A
0N/A /** Provides the footer text for the table. */
0N/A private MessageFormat footerFormat;
0N/A
0N/A /** The most recent page index asked to print. */
0N/A private int last = -1;
0N/A
0N/A /** The next row to print. */
0N/A private int row = 0;
0N/A
0N/A /** The next column to print. */
0N/A private int col = 0;
0N/A
0N/A /** Used to store an area of the table to be printed. */
0N/A private final Rectangle clip = new Rectangle(0, 0, 0, 0);
0N/A
0N/A /** Used to store an area of the table's header to be printed. */
0N/A private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
0N/A
0N/A /** Saves the creation of multiple rectangles. */
0N/A private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
0N/A
0N/A /** Vertical space to leave between table and header/footer text. */
0N/A private static final int H_F_SPACE = 8;
0N/A
0N/A /** Font size for the header text. */
0N/A private static final float HEADER_FONT_SIZE = 18.0f;
0N/A
0N/A /** Font size for the footer text. */
0N/A private static final float FOOTER_FONT_SIZE = 12.0f;
0N/A
0N/A /** The font to use in rendering header text. */
0N/A private Font headerFont;
0N/A
0N/A /** The font to use in rendering footer text. */
0N/A private Font footerFont;
0N/A
0N/A /**
0N/A * Create a new <code>TablePrintable</code> for the given
0N/A * <code>JTable</code>. Header and footer text can be specified using the
0N/A * two <code>MessageFormat</code> parameters. When called upon to provide
0N/A * a String, each format is given the current page number.
0N/A *
0N/A * @param table the table to print
0N/A * @param printMode the printing mode for this printable
0N/A * @param headerFormat a <code>MessageFormat</code> specifying the text to
0N/A * be used in printing a header, or null for none
0N/A * @param footerFormat a <code>MessageFormat</code> specifying the text to
0N/A * be used in printing a footer, or null for none
0N/A * @throws IllegalArgumentException if passed an invalid print mode
0N/A */
0N/A public TablePrintable(JTable table,
0N/A JTable.PrintMode printMode,
0N/A MessageFormat headerFormat,
0N/A MessageFormat footerFormat) {
0N/A
0N/A this.table = table;
0N/A
0N/A header = table.getTableHeader();
0N/A colModel = table.getColumnModel();
0N/A totalColWidth = colModel.getTotalColumnWidth();
0N/A
0N/A if (header != null) {
0N/A // the header clip height can be set once since it's unchanging
0N/A hclip.height = header.getHeight();
0N/A }
0N/A
0N/A this.printMode = printMode;
0N/A
0N/A this.headerFormat = headerFormat;
0N/A this.footerFormat = footerFormat;
0N/A
0N/A // derive the header and footer font from the table's font
0N/A headerFont = table.getFont().deriveFont(Font.BOLD,
0N/A HEADER_FONT_SIZE);
0N/A footerFont = table.getFont().deriveFont(Font.PLAIN,
0N/A FOOTER_FONT_SIZE);
0N/A }
0N/A
0N/A /**
0N/A * Prints the specified page of the table into the given {@link Graphics}
0N/A * context, in the specified format.
0N/A *
0N/A * @param graphics the context into which the page is drawn
0N/A * @param pageFormat the size and orientation of the page being drawn
0N/A * @param pageIndex the zero based index of the page to be drawn
0N/A * @return PAGE_EXISTS if the page is rendered successfully, or
0N/A * NO_SUCH_PAGE if a non-existent page index is specified
0N/A * @throws PrinterException if an error causes printing to be aborted
0N/A */
0N/A public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
0N/A throws PrinterException {
0N/A
0N/A // for easy access to these values
0N/A final int imgWidth = (int)pageFormat.getImageableWidth();
0N/A final int imgHeight = (int)pageFormat.getImageableHeight();
0N/A
0N/A if (imgWidth <= 0) {
0N/A throw new PrinterException("Width of printable area is too small.");
0N/A }
0N/A
0N/A // to pass the page number when formatting the header and footer text
215N/A Object[] pageNumber = new Object[]{Integer.valueOf(pageIndex + 1)};
0N/A
0N/A // fetch the formatted header text, if any
0N/A String headerText = null;
0N/A if (headerFormat != null) {
0N/A headerText = headerFormat.format(pageNumber);
0N/A }
0N/A
0N/A // fetch the formatted footer text, if any
0N/A String footerText = null;
0N/A if (footerFormat != null) {
0N/A footerText = footerFormat.format(pageNumber);
0N/A }
0N/A
0N/A // to store the bounds of the header and footer text
0N/A Rectangle2D hRect = null;
0N/A Rectangle2D fRect = null;
0N/A
0N/A // the amount of vertical space needed for the header and footer text
0N/A int headerTextSpace = 0;
0N/A int footerTextSpace = 0;
0N/A
0N/A // the amount of vertical space available for printing the table
0N/A int availableSpace = imgHeight;
0N/A
0N/A // if there's header text, find out how much space is needed for it
0N/A // and subtract that from the available space
0N/A if (headerText != null) {
0N/A graphics.setFont(headerFont);
0N/A hRect = graphics.getFontMetrics().getStringBounds(headerText,
0N/A graphics);
0N/A
0N/A headerTextSpace = (int)Math.ceil(hRect.getHeight());
0N/A availableSpace -= headerTextSpace + H_F_SPACE;
0N/A }
0N/A
0N/A // if there's footer text, find out how much space is needed for it
0N/A // and subtract that from the available space
0N/A if (footerText != null) {
0N/A graphics.setFont(footerFont);
0N/A fRect = graphics.getFontMetrics().getStringBounds(footerText,
0N/A graphics);
0N/A
0N/A footerTextSpace = (int)Math.ceil(fRect.getHeight());
0N/A availableSpace -= footerTextSpace + H_F_SPACE;
0N/A }
0N/A
0N/A if (availableSpace <= 0) {
0N/A throw new PrinterException("Height of printable area is too small.");
0N/A }
0N/A
0N/A // depending on the print mode, we may need a scale factor to
0N/A // fit the table's entire width on the page
0N/A double sf = 1.0D;
0N/A if (printMode == JTable.PrintMode.FIT_WIDTH &&
0N/A totalColWidth > imgWidth) {
0N/A
0N/A // if not, we would have thrown an acception previously
0N/A assert imgWidth > 0;
0N/A
0N/A // it must be, according to the if-condition, since imgWidth > 0
0N/A assert totalColWidth > 1;
0N/A
0N/A sf = (double)imgWidth / (double)totalColWidth;
0N/A }
0N/A
0N/A // dictated by the previous two assertions
0N/A assert sf > 0;
0N/A
0N/A // This is in a loop for two reasons:
0N/A // First, it allows us to catch up in case we're called starting
0N/A // with a non-zero pageIndex. Second, we know that we can be called
0N/A // for the same page multiple times. The condition of this while
0N/A // loop acts as a check, ensuring that we don't attempt to do the
0N/A // calculations again when we are called subsequent times for the
0N/A // same page.
0N/A while (last < pageIndex) {
0N/A // if we are finished all columns in all rows
0N/A if (row >= table.getRowCount() && col == 0) {
0N/A return NO_SUCH_PAGE;
0N/A }
0N/A
0N/A // rather than multiplying every row and column by the scale factor
0N/A // in findNextClip, just pass a width and height that have already
0N/A // been divided by it
0N/A int scaledWidth = (int)(imgWidth / sf);
0N/A int scaledHeight = (int)((availableSpace - hclip.height) / sf);
0N/A
0N/A // calculate the area of the table to be printed for this page
0N/A findNextClip(scaledWidth, scaledHeight);
0N/A
0N/A last++;
0N/A }
0N/A
0N/A // create a copy of the graphics so we don't affect the one given to us
0N/A Graphics2D g2d = (Graphics2D)graphics.create();
0N/A
0N/A // translate into the co-ordinate system of the pageFormat
0N/A g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
0N/A
0N/A // to save and store the transform
0N/A AffineTransform oldTrans;
0N/A
0N/A // if there's footer text, print it at the bottom of the imageable area
0N/A if (footerText != null) {
0N/A oldTrans = g2d.getTransform();
0N/A
0N/A g2d.translate(0, imgHeight - footerTextSpace);
0N/A
0N/A printText(g2d, footerText, fRect, footerFont, imgWidth);
0N/A
0N/A g2d.setTransform(oldTrans);
0N/A }
0N/A
0N/A // if there's header text, print it at the top of the imageable area
0N/A // and then translate downwards
0N/A if (headerText != null) {
0N/A printText(g2d, headerText, hRect, headerFont, imgWidth);
0N/A
0N/A g2d.translate(0, headerTextSpace + H_F_SPACE);
0N/A }
0N/A
0N/A // constrain the table output to the available space
0N/A tempRect.x = 0;
0N/A tempRect.y = 0;
0N/A tempRect.width = imgWidth;
0N/A tempRect.height = availableSpace;
0N/A g2d.clip(tempRect);
0N/A
0N/A // if we have a scale factor, scale the graphics object to fit
0N/A // the entire width
0N/A if (sf != 1.0D) {
0N/A g2d.scale(sf, sf);
0N/A
0N/A // otherwise, ensure that the current portion of the table is
0N/A // centered horizontally
0N/A } else {
0N/A int diff = (imgWidth - clip.width) / 2;
0N/A g2d.translate(diff, 0);
0N/A }
0N/A
0N/A // store the old transform and clip for later restoration
0N/A oldTrans = g2d.getTransform();
0N/A Shape oldClip = g2d.getClip();
0N/A
0N/A // if there's a table header, print the current section and
0N/A // then translate downwards
0N/A if (header != null) {
0N/A hclip.x = clip.x;
0N/A hclip.width = clip.width;
0N/A
0N/A g2d.translate(-hclip.x, 0);
0N/A g2d.clip(hclip);
0N/A header.print(g2d);
0N/A
0N/A // restore the original transform and clip
0N/A g2d.setTransform(oldTrans);
0N/A g2d.setClip(oldClip);
0N/A
0N/A // translate downwards
0N/A g2d.translate(0, hclip.height);
0N/A }
0N/A
0N/A // print the current section of the table
0N/A g2d.translate(-clip.x, -clip.y);
0N/A g2d.clip(clip);
0N/A table.print(g2d);
0N/A
0N/A // restore the original transform and clip
0N/A g2d.setTransform(oldTrans);
0N/A g2d.setClip(oldClip);
0N/A
0N/A // draw a box around the table
0N/A g2d.setColor(Color.BLACK);
0N/A g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
0N/A
0N/A // dispose the graphics copy
0N/A g2d.dispose();
0N/A
0N/A return PAGE_EXISTS;
0N/A }
0N/A
0N/A /**
0N/A * A helper method that encapsulates common code for rendering the
0N/A * header and footer text.
0N/A *
0N/A * @param g2d the graphics to draw into
0N/A * @param text the text to draw, non null
0N/A * @param rect the bounding rectangle for this text,
0N/A * as calculated at the given font, non null
0N/A * @param font the font to draw the text in, non null
0N/A * @param imgWidth the width of the area to draw into
0N/A */
0N/A private void printText(Graphics2D g2d,
0N/A String text,
0N/A Rectangle2D rect,
0N/A Font font,
0N/A int imgWidth) {
0N/A
0N/A int tx;
0N/A
0N/A // if the text is small enough to fit, center it
0N/A if (rect.getWidth() < imgWidth) {
0N/A tx = (int)((imgWidth - rect.getWidth()) / 2);
0N/A
0N/A // otherwise, if the table is LTR, ensure the left side of
0N/A // the text shows; the right can be clipped
0N/A } else if (table.getComponentOrientation().isLeftToRight()) {
0N/A tx = 0;
0N/A
0N/A // otherwise, ensure the right side of the text shows
0N/A } else {
0N/A tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
0N/A }
0N/A
0N/A int ty = (int)Math.ceil(Math.abs(rect.getY()));
0N/A g2d.setColor(Color.BLACK);
0N/A g2d.setFont(font);
0N/A g2d.drawString(text, tx, ty);
0N/A }
0N/A
0N/A /**
0N/A * Calculate the area of the table to be printed for
0N/A * the next page. This should only be called if there
0N/A * are rows and columns left to print.
0N/A *
0N/A * To avoid an infinite loop in printing, this will
0N/A * always put at least one cell on each page.
0N/A *
0N/A * @param pw the width of the area to print in
0N/A * @param ph the height of the area to print in
0N/A */
0N/A private void findNextClip(int pw, int ph) {
0N/A final boolean ltr = table.getComponentOrientation().isLeftToRight();
0N/A
0N/A // if we're ready to start a new set of rows
0N/A if (col == 0) {
0N/A if (ltr) {
0N/A // adjust clip to the left of the first column
0N/A clip.x = 0;
0N/A } else {
0N/A // adjust clip to the right of the first column
0N/A clip.x = totalColWidth;
0N/A }
0N/A
0N/A // adjust clip to the top of the next set of rows
0N/A clip.y += clip.height;
0N/A
0N/A // adjust clip width and height to be zero
0N/A clip.width = 0;
0N/A clip.height = 0;
0N/A
0N/A // fit as many rows as possible, and at least one
0N/A int rowCount = table.getRowCount();
0N/A int rowHeight = table.getRowHeight(row);
0N/A do {
0N/A clip.height += rowHeight;
0N/A
0N/A if (++row >= rowCount) {
0N/A break;
0N/A }
0N/A
0N/A rowHeight = table.getRowHeight(row);
0N/A } while (clip.height + rowHeight <= ph);
0N/A }
0N/A
0N/A // we can short-circuit for JTable.PrintMode.FIT_WIDTH since
0N/A // we'll always fit all columns on the page
0N/A if (printMode == JTable.PrintMode.FIT_WIDTH) {
0N/A clip.x = 0;
0N/A clip.width = totalColWidth;
0N/A return;
0N/A }
0N/A
0N/A if (ltr) {
0N/A // adjust clip to the left of the next set of columns
0N/A clip.x += clip.width;
0N/A }
0N/A
0N/A // adjust clip width to be zero
0N/A clip.width = 0;
0N/A
0N/A // fit as many columns as possible, and at least one
0N/A int colCount = table.getColumnCount();
0N/A int colWidth = colModel.getColumn(col).getWidth();
0N/A do {
0N/A clip.width += colWidth;
0N/A if (!ltr) {
0N/A clip.x -= colWidth;
0N/A }
0N/A
0N/A if (++col >= colCount) {
0N/A // reset col to 0 to indicate we're finished all columns
0N/A col = 0;
0N/A
0N/A break;
0N/A }
0N/A
0N/A colWidth = colModel.getColumn(col).getWidth();
0N/A } while (clip.width + colWidth <= pw);
0N/A
0N/A }
0N/A
0N/A}