01: package com.pk;
02:
03: import javax.swing.*; //import javax.swing.table.*;
04:
05: import java.awt.print.*; //import java.util.*;
06: import java.awt.*;
07:
08: //import java.awt.event.*;
09: //import java.awt.geom.*;
10: //import java.awt.Dimension;
11:
12: public class PrintTable implements Printable {
13:
14: JFrame frame;
15: JTable tableView;
16:
17: public void setJTable(JTable argJTable) {
18: tableView = argJTable;
19: }
20:
21: public void doPrintJTable() {
22: PrinterJob pj = PrinterJob.getPrinterJob();
23:
24: pj.setPrintable(this );
25:
26: try {
27: if (pj.printDialog()) {
28: pj.print();
29: }
30: } catch (Exception PrintException) {
31: }
32:
33: }
34:
35: public int print(Graphics g, PageFormat pageFormat, int pageIndex)
36: throws PrinterException {
37:
38: Graphics2D g2 = (Graphics2D) g;
39: g2.setColor(Color.black);
40: int fontHeight = g2.getFontMetrics().getHeight();
41: int fontDesent = g2.getFontMetrics().getDescent();
42:
43: //leave room for page number
44: double pageHeight = pageFormat.getImageableHeight()
45: - fontHeight;
46:
47: double pageWidth = pageFormat.getImageableWidth();
48: double tableWidth = (double) tableView.getColumnModel()
49: .getTotalColumnWidth();
50: double scale = 1;
51: if (tableWidth >= pageWidth) {
52: scale = pageWidth / tableWidth;
53: }
54:
55: double headerHeightOnPage = tableView.getTableHeader()
56: .getHeight()
57: * scale;
58: double tableWidthOnPage = tableWidth * scale;
59:
60: double oneRowHeight = (tableView.getRowHeight() + tableView
61: .getRowMargin())
62: * scale;
63: int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage) / oneRowHeight);
64: double pageHeightForTable = oneRowHeight * numRowsOnAPage;
65: int totalNumPages = (int) Math.ceil(((double) tableView
66: .getRowCount())
67: / numRowsOnAPage);
68: if (pageIndex >= totalNumPages) {
69: return NO_SUCH_PAGE;
70: }
71:
72: g2.translate(pageFormat.getImageableX(), pageFormat
73: .getImageableY());
74: g2.drawString("Page: " + (pageIndex + 1),
75: (int) pageWidth / 2 - 35, (int) (pageHeight
76: + fontHeight - fontDesent));
77: //bottom center
78:
79: g2.translate(0f, headerHeightOnPage);
80: g2.translate(0f, -pageIndex * pageHeightForTable);
81: //TODO this next line treats the last page as a full page
82: g2.setClip(0, (int) (pageHeightForTable * pageIndex),
83: (int) Math.ceil(tableWidthOnPage), (int) Math
84: .ceil(pageHeightForTable));
85:
86: g2.scale(scale, scale);
87: tableView.paint(g2);
88: g2.scale(1 / scale, 1 / scale);
89: g2.translate(0f, pageIndex * pageHeightForTable);
90: g2.translate(0f, -headerHeightOnPage);
91: g2.setClip(0, 0, (int) Math.ceil(tableWidthOnPage), (int) Math
92: .ceil(headerHeightOnPage));
93: g2.scale(scale, scale);
94: tableView.getTableHeader().paint(g2); //paint header at top
95:
96: return Printable.PAGE_EXISTS;
97: }
98:
99: }
|