KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > javax > swing > TablePrintable


1 /*
2  * @(#)TablePrintable.java 1.39 03/12/19
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7
8 package javax.swing;
9
10 import javax.swing.table.*;
11 import java.awt.*;
12 import java.awt.print.*;
13 import java.awt.geom.*;
14 import java.text.MessageFormat JavaDoc;
15
16 /**
17  * An implementation of <code>Printable</code> for printing
18  * <code>JTable</code>s.
19  * <p>
20  * This implementation spreads table rows naturally in sequence
21  * across multiple pages, fitting as many rows as possible per page.
22  * The distribution of columns, on the other hand, is controlled by a
23  * printing mode parameter passed to the constructor. When
24  * <code>JTable.PrintMode.NORMAL</code> is used, the implementation
25  * handles columns in a similar manner to how it handles rows, spreading them
26  * across multiple pages (in an order consistent with the table's
27  * <code>ComponentOrientation</code>).
28  * When <code>JTable.PrintMode.FIT_WIDTH</code> is given, the implementation
29  * scales the output smaller if necessary, to ensure that all columns fit on
30  * the page. (Note that width and height are scaled equally, ensuring that the
31  * aspect ratio remains the same).
32  * <p>
33  * The portion of table printed on each page is headed by the
34  * appropriate section of the table's <code>JTableHeader</code>.
35  * <p>
36  * Header and footer text can be added to the output by providing
37  * <code>MessageFormat</code> instances to the constructor. The
38  * printing code requests Strings from the formats by calling
39  * their <code>format</code> method with a single parameter:
40  * an <code>Object</code> array containing a single element of type
41  * <code>Integer</code>, representing the current page number.
42  * <p>
43  * There are certain circumstances where this <code>Printable<code>
44  * cannot fit items appropriately, resulting in clipped output.
45  * These are:
46  * <ul>
47  * <li>In any mode, when the header or footer text is too wide to
48  * fit completely in the printable area. The implementation
49  * prints as much of the text as possible starting from the beginning,
50  * as determined by the table's <code>ComponentOrientation</code>.
51  * <li>In any mode, when a row is too tall to fit in the
52  * printable area. The upper most portion of the row
53  * is printed and no lower border is shown.
54  * <li>In <code>JTable.PrintMode.NORMAL</code> when a column
55  * is too wide to fit in the printable area. The center of the
56  * column is printed and no left and right borders are shown.
57  * </ul>
58  * <p>
59  * It is entirely valid for a developer to wrap this <code>Printable</code>
60  * inside another in order to create complex reports and documents. They may
61  * even request that different pages be rendered into different sized
62  * printable areas. The implementation was designed to handle this by
63  * performing most of its calculations on the fly. However, providing different
64  * sizes works best when <code>JTable.PrintMode.FIT_WIDTH</code> is used, or
65  * when only the printable width is changed between pages. This is because when
66  * it is printing a set of rows in <code>JTable.PrintMode.NORMAL</code> and the
67  * implementation determines a need to distribute columns across pages,
68  * it assumes that all of those rows will fit on each subsequent page needed
69  * to fit the columns.
70  * <p>
71  * It is the responsibility of the developer to ensure that the table is not
72  * modified in any way after this <code>Printable</code> is created (invalid
73  * modifications include changes in: size, renderers, or underlying data).
74  * The behavior of this <code>Printable</code> is undefined if the table is
75  * changed at any time after creation.
76  *
77  * @author Shannon Hickey
78  * @version 1.39 12/19/03
79  */

80 class TablePrintable implements Printable {
81
82     /** The table to print. */
83     private JTable JavaDoc table;
84
85     /** For quick reference to the table's header. */
86     private JTableHeader header;
87
88     /** For quick reference to the table's column model. */
89     private TableColumnModel colModel;
90
91     /** To save multiple calculations of total column width. */
92     private int totalColWidth;
93
94     /** The printing mode of this printable. */
95     private JTable.PrintMode JavaDoc printMode;
96
97     /** Provides the header text for the table. */
98     private MessageFormat JavaDoc headerFormat;
99
100     /** Provides the footer text for the table. */
101     private MessageFormat JavaDoc footerFormat;
102
103     /** The most recent page index asked to print. */
104     private int last = -1;
105
106     /** The next row to print. */
107     private int row = 0;
108
109     /** The next column to print. */
110     private int col = 0;
111
112     /** Used to store an area of the table to be printed. */
113     private final Rectangle clip = new Rectangle(0, 0, 0, 0);
114
115     /** Used to store an area of the table's header to be printed. */
116     private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
117
118     /** Saves the creation of multiple rectangles. */
119     private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
120
121     /** Vertical space to leave between table and header/footer text. */
122     private static final int H_F_SPACE = 8;
123
124     /** Font size for the header text. */
125     private static final float HEADER_FONT_SIZE = 18.0f;
126
127     /** Font size for the footer text. */
128     private static final float FOOTER_FONT_SIZE = 12.0f;
129
130     /** The font to use in rendering header text. */
131     private Font headerFont;
132
133     /** The font to use in rendering footer text. */
134     private Font footerFont;
135
136     /**
137      * Create a new <code>TablePrintable<code> for the given
138      * <code>JTable</code>. Header and footer text can be specified using the
139      * two <code>MessageFormat</code> parameters. When called upon to provide
140      * a String, each format is given the current page number.
141      *
142      * @param table the table to print
143      * @param printMode the printing mode for this printable
144      * @param headerFormat a <code>MessageFormat</code> specifying the text to
145      * be used in printing a header, or null for none
146      * @param footerFormat a <code>MessageFormat</code> specifying the text to
147      * be used in printing a footer, or null for none
148      * @throws IllegalArgumentException if passed an invalid print mode
149      */

150     public TablePrintable(JTable JavaDoc table,
151                           JTable.PrintMode JavaDoc printMode,
152                           MessageFormat JavaDoc headerFormat,
153                           MessageFormat JavaDoc footerFormat) {
154
155         this.table = table;
156
157         header = table.getTableHeader();
158         colModel = table.getColumnModel();
159         totalColWidth = colModel.getTotalColumnWidth();
160         
161         if (header != null) {
162             // the header clip height can be set once since it's unchanging
163
hclip.height = header.getHeight();
164         }
165
166         this.printMode = printMode;
167
168         this.headerFormat = headerFormat;
169         this.footerFormat = footerFormat;
170
171         // derive the header and footer font from the table's font
172
headerFont = table.getFont().deriveFont(Font.BOLD,
173                                                 HEADER_FONT_SIZE);
174         footerFont = table.getFont().deriveFont(Font.PLAIN,
175                                                 FOOTER_FONT_SIZE);
176     }
177
178     /**
179      * Prints the specified page of the table into the given {@link Graphics}
180      * context, in the specified format.
181      *
182      * @param graphics the context into which the page is drawn
183      * @param pageFormat the size and orientation of the page being drawn
184      * @param pageIndex the zero based index of the page to be drawn
185      * @return PAGE_EXISTS if the page is rendered successfully, or
186      * NO_SUCH_PAGE if a non-existent page index is specified
187      * @throws PrinterException if an error causes printing to be aborted
188      */

189     public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
190                                                        throws PrinterException {
191
192         // for easy access to these values
193
final int imgWidth = (int)pageFormat.getImageableWidth();
194         final int imgHeight = (int)pageFormat.getImageableHeight();
195
196         if (imgWidth <= 0) {
197             throw new PrinterException("Width of printable area is too small.");
198         }
199
200         // to pass the page number when formatting the header and footer text
201
Object JavaDoc[] pageNumber = new Object JavaDoc[]{new Integer JavaDoc(pageIndex + 1)};
202
203         // fetch the formatted header text, if any
204
String JavaDoc headerText = null;
205         if (headerFormat != null) {
206             headerText = headerFormat.format(pageNumber);
207         }
208
209         // fetch the formatted footer text, if any
210
String JavaDoc footerText = null;
211         if (footerFormat != null) {
212             footerText = footerFormat.format(pageNumber);
213         }
214
215         // to store the bounds of the header and footer text
216
Rectangle2D hRect = null;
217         Rectangle2D fRect = null;
218
219         // the amount of vertical space needed for the header and footer text
220
int headerTextSpace = 0;
221         int footerTextSpace = 0;
222
223         // the amount of vertical space available for printing the table
224
int availableSpace = imgHeight;
225
226         // if there's header text, find out how much space is needed for it
227
// and subtract that from the available space
228
if (headerText != null) {
229             graphics.setFont(headerFont);
230             hRect = graphics.getFontMetrics().getStringBounds(headerText,
231                                                               graphics);
232
233             headerTextSpace = (int)Math.ceil(hRect.getHeight());
234             availableSpace -= headerTextSpace + H_F_SPACE;
235         }
236
237         // if there's footer text, find out how much space is needed for it
238
// and subtract that from the available space
239
if (footerText != null) {
240             graphics.setFont(footerFont);
241             fRect = graphics.getFontMetrics().getStringBounds(footerText,
242                                                               graphics);
243
244             footerTextSpace = (int)Math.ceil(fRect.getHeight());
245             availableSpace -= footerTextSpace + H_F_SPACE;
246         }
247
248         if (availableSpace <= 0) {
249             throw new PrinterException("Height of printable area is too small.");
250         }
251
252         // depending on the print mode, we may need a scale factor to
253
// fit the table's entire width on the page
254
double sf = 1.0D;
255         if (printMode == JTable.PrintMode.FIT_WIDTH &&
256                 totalColWidth > imgWidth) {
257
258             // if not, we would have thrown an acception previously
259
assert imgWidth > 0;
260
261             // it must be, according to the if-condition, since imgWidth > 0
262
assert totalColWidth > 1;
263
264             sf = (double)imgWidth / (double)totalColWidth;
265         }
266
267         // dictated by the previous two assertions
268
assert sf > 0;
269
270         // This is in a loop for two reasons:
271
// First, it allows us to catch up in case we're called starting
272
// with a non-zero pageIndex. Second, we know that we can be called
273
// for the same page multiple times. The condition of this while
274
// loop acts as a check, ensuring that we don't attempt to do the
275
// calculations again when we are called subsequent times for the
276
// same page.
277
while (last < pageIndex) {
278             // if we are finished all columns in all rows
279
if (row >= table.getRowCount() && col == 0) {
280                 return NO_SUCH_PAGE;
281             }
282
283             // rather than multiplying every row and column by the scale factor
284
// in findNextClip, just pass a width and height that have already
285
// been divided by it
286
int scaledWidth = (int)(imgWidth / sf);
287             int scaledHeight = (int)((availableSpace - hclip.height) / sf);
288
289             // calculate the area of the table to be printed for this page
290
findNextClip(scaledWidth, scaledHeight);
291
292             last++;
293         }
294
295         // translate into the co-ordinate system of the pageFormat
296
Graphics2D g2d = (Graphics2D)graphics;
297         g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
298         
299         // to save and store the transform
300
AffineTransform oldTrans;
301         
302         // if there's footer text, print it at the bottom of the imageable area
303
if (footerText != null) {
304             oldTrans = g2d.getTransform();
305
306             g2d.translate(0, imgHeight - footerTextSpace);
307
308             printText(g2d, footerText, fRect, footerFont, imgWidth);
309
310             g2d.setTransform(oldTrans);
311         }
312
313         // if there's header text, print it at the top of the imageable area
314
// and then translate downwards
315
if (headerText != null) {
316             printText(g2d, headerText, hRect, headerFont, imgWidth);
317
318             g2d.translate(0, headerTextSpace + H_F_SPACE);
319         }
320
321         // constrain the table output to the available space
322
tempRect.x = 0;
323         tempRect.y = 0;
324         tempRect.width = imgWidth;
325         tempRect.height = availableSpace;
326         g2d.clip(tempRect);
327
328         // if we have a scale factor, scale the graphics object to fit
329
// the entire width
330
if (sf != 1.0D) {
331             g2d.scale(sf, sf);
332
333         // otherwise, ensure that the current portion of the table is
334
// centered horizontally
335
} else {
336             int diff = (imgWidth - clip.width) / 2;
337             g2d.translate(diff, 0);
338         }
339
340         // store the old transform and clip for later restoration
341
oldTrans = g2d.getTransform();
342         Shape oldClip = g2d.getClip();
343
344         // if there's a table header, print the current section and
345
// then translate downwards
346
if (header != null) {
347             hclip.x = clip.x;
348             hclip.width = clip.width;
349
350             g2d.translate(-hclip.x, 0);
351             g2d.clip(hclip);
352             header.print(g2d);
353
354             // restore the original transform and clip
355
g2d.setTransform(oldTrans);
356             g2d.setClip(oldClip);
357
358             // translate downwards
359
g2d.translate(0, hclip.height);
360         }
361
362         // print the current section of the table
363
g2d.translate(-clip.x, -clip.y);
364         g2d.clip(clip);
365         table.print(g2d);
366         
367         // restore the original transform and clip
368
g2d.setTransform(oldTrans);
369         g2d.setClip(oldClip);
370         
371         // draw a box around the table
372
g2d.setColor(Color.BLACK);
373         g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
374
375         return PAGE_EXISTS;
376     }
377
378     /**
379      * A helper method that encapsulates common code for rendering the
380      * header and footer text.
381      *
382      * @param g2d the graphics to draw into
383      * @param text the text to draw, non null
384      * @param rect the bounding rectangle for this text,
385      * as calculated at the given font, non null
386      * @param font the font to draw the text in, non null
387      * @param imgWidth the width of the area to draw into
388      */

389     private void printText(Graphics2D g2d,
390                            String JavaDoc text,
391                            Rectangle2D rect,
392                            Font font,
393                            int imgWidth) {
394
395             int tx;
396
397             // if the text is small enough to fit, center it
398
if (rect.getWidth() < imgWidth) {
399                 tx = (int)((imgWidth - rect.getWidth()) / 2);
400
401             // otherwise, if the table is LTR, ensure the left side of
402
// the text shows; the right can be clipped
403
} else if (table.getComponentOrientation().isLeftToRight()) {
404                 tx = 0;
405
406             // otherwise, ensure the right side of the text shows
407
} else {
408                 tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
409             }
410
411             int ty = (int)Math.ceil(Math.abs(rect.getY()));
412             g2d.setColor(Color.BLACK);
413             g2d.setFont(font);
414             g2d.drawString(text, tx, ty);
415     }
416
417     /**
418      * Calculate the area of the table to be printed for
419      * the next page. This should only be called if there
420      * are rows and columns left to print.
421      *
422      * To avoid an infinite loop in printing, this will
423      * always put at least one cell on each page.
424      *
425      * @param pw the width of the area to print in
426      * @param ph the height of the area to print in
427      */

428     private void findNextClip(int pw, int ph) {
429         final boolean ltr = table.getComponentOrientation().isLeftToRight();
430
431         // if we're ready to start a new set of rows
432
if (col == 0) {
433             if (ltr) {
434                 // adjust clip to the left of the first column
435
clip.x = 0;
436             } else {
437                 // adjust clip to the right of the first column
438
clip.x = totalColWidth;
439             }
440
441             // adjust clip to the top of the next set of rows
442
clip.y += clip.height;
443             
444             // adjust clip width and height to be zero
445
clip.width = 0;
446             clip.height = 0;
447
448             // fit as many rows as possible, and at least one
449
int rowCount = table.getRowCount();
450             int rowHeight = table.getRowHeight(row);
451             do {
452                 clip.height += rowHeight;
453
454                 if (++row >= rowCount) {
455                     break;
456                 }
457
458                 rowHeight = table.getRowHeight(row);
459             } while (clip.height + rowHeight <= ph);
460         }
461
462         // we can short-circuit for JTable.PrintMode.FIT_WIDTH since
463
// we'll always fit all columns on the page
464
if (printMode == JTable.PrintMode.FIT_WIDTH) {
465             clip.x = 0;
466             clip.width = totalColWidth;
467             return;
468         }
469
470         if (ltr) {
471             // adjust clip to the left of the next set of columns
472
clip.x += clip.width;
473         }
474
475         // adjust clip width to be zero
476
clip.width = 0;
477
478         // fit as many columns as possible, and at least one
479
int colCount = table.getColumnCount();
480         int colWidth = colModel.getColumn(col).getWidth();
481         do {
482             clip.width += colWidth;
483             if (!ltr) {
484                 clip.x -= colWidth;
485             }
486
487             if (++col >= colCount) {
488                 // reset col to 0 to indicate we're finished all columns
489
col = 0;
490
491                 break;
492             }
493
494             colWidth = colModel.getColumn(col).getWidth();
495         } while (clip.width + colWidth <= pw);
496
497     }
498
499 }
500
Popular Tags