Printing JTable

Hi
I ahve created a print method in order to print various reports. However, This is set up to print results of queries. One of the reports that I wish to report is a lot more complicated than just a query...and realistically I need to print a JTable, which displays the result of some calculations.
Ive tried just passing a JTable instead of a query as the parameter, however as you will see below, what I set up to print is a TextArea that appends text. Due to this I cannot simply append the JTable. I was wondering, is there a way of printing this JTable. Code as follows:
public PrintMortgageSearch(String query) {
        super("Printing Result of Search", false, true, false, true);
        //for getting the graphical user interface components display area
        Container cp = getContentPane();
        //for setting the font
        textArea.setFont(new Font("Tahoma", Font.PLAIN, 9));
        //for adding the textarea to the container
        cp.add(textArea);
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            con = DriverManager.getConnection(url, "myLogin", "myPassword");
        catch (ClassNotFoundException ea) {
            System.out.println(ea.toString());
        catch (Exception e) {
            System.out.println(e.toString());
        try {
            statement = con.createStatement();
            resultset = statement.executeQuery(query);
            textArea.append("=============== Results of Search ===============\n\n");
            while (resultset.next()) {
                textArea.append("Lender: " + resultset.getString(1) + "\t" +
                "Product: " + resultset.getString(2) + "\t" +
                "Term: " + resultset.getString(3) + "\t" +
                "Rate: " + resultset.getString(4) + "\t" +
                "APR: " + resultset.getString(5) + "\t" +
                "Cost: " + resultset.getString(6) + "\t"+"\n\n");
            textArea.append("=============== Results of Search ===============");
            resultset.close();
            statement.close();
            con.close();
        catch (SQLException SQLe) {
            System.out.println(SQLe.toString());
        //for setting the visible to true
        setVisible(true);
        //to show the frame
        pack();
    }Id like to just append the JTable to the TextArea rather than using the DB connection as above.
Is this possible?
Thanking you in advance

Actually, Im having a problem!
The JTable doesnt fit on the page.
Ive tried adjusting the
paper.setImageableArea(0, 0.5D*72, 4.267D*72, 10.652D*72);
       paper.setSize(6.267D*72, 11.692D*72);these figures are reduced on what it was previously...but everytime I lower the width and height figures theres no difference in the size at all!
Does anyone know what exactly it is that I have to change

Similar Messages

  • Is it possible to print JTable and custom JPanel on the same page?

    Hello everybody!
    I have a custom panel extending JPanel and implementing Printable.
    I am using paint() method to draw some graphics on it's content pane. I would like to print it, but first I would like to add a JTable at the bottom of my panel. Printing just the panel goes well. No problems with that.
    I was also able to add a JTable to the bottom of JFrame, which contains my panel.
    But how can I print those two components on one page?

    Hi, thanks for your answer, but I thought about that earlier and that doesn't work as well... or mybe I'm doing something wrong. Here is the sample code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    public class ReportFrame extends JFrame implements Printable {
         private static final long serialVersionUID = -8291124097290245799L;
         private MyPanel rp;
         private JTable reportTable;
         private HashPrintRequestAttributeSet attributes;
         public ReportFrame() {
              rp = new MyPanel();
              String[] columnNames = { "Column1", "Column2", "Column3" };
              String[][] values = { { "Value1", "Value2", "Value3" }, { "Value4", "Value5", "Value6" }, { "Value7", "Value8", "Value9" } };
              reportTable = new JTable(values, columnNames);
              add(rp, BorderLayout.CENTER);
              add(reportTable, BorderLayout.SOUTH);
              setTitle("Printing example");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setPreferredSize(new Dimension(700, 700));
              pack();
              setVisible(true);
         @Override
         public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
              if (pageIndex >= 1)
                   return Printable.NO_SUCH_PAGE;
              Graphics2D g2D = (Graphics2D) graphics;
              g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              return Printable.PAGE_EXISTS;
         public static void main(String[] args) {
              new ReportFrame().printer();
         class MyPanel extends JPanel implements Printable {
              private static final long serialVersionUID = -2214177603101440610L;
              @Override
              public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
                   if (pageIndex >= 1)
                        return Printable.NO_SUCH_PAGE;
                   Graphics2D g2D = (Graphics2D) graphics;
                   g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                   return Printable.PAGE_EXISTS;
              @Override
              public void paint(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D) g;
                   int x = 0, y = 0, width = 70, height = 70;
                   for (int i = 0; i < 50; i++) {
                        g2D.drawOval(x + i * 10, y + i * 10, width, height);
         public void printer() {
              try {
                   attributes = new HashPrintRequestAttributeSet();
                   PrinterJob job = PrinterJob.getPrinterJob();
                   job.setPrintable(this);
                   if (job.printDialog(attributes))
                        job.print(attributes);
              } catch (PrinterException e) {
                   JOptionPane.showMessageDialog(this, e);
    }UPDATE:
    I've managed to get this to work, by calling 2 methods inside the outer frame's print method (lines 78 and 79)
    Those two methods are:
    rp.paint(g2D);
    reportTable.paint(g2D);but still it is not the way I would like it to be.
    First of all both the ReportPanel and ReportTable graphics are printed with the upper-left corner located in the upper-left corner of the JFrame and the first one is covering the second.
    Secondly, I would like to rather implemet the robust JTable's print method somehow, because it has some neat features like multipage printing, headers & footers. But I have no idea how to add my own graphics to the JTables print method, so they will appear above the JTable. Maybe someone knows the answer?
    Thanks a lot
    UPDATE2:
    I was googling nearly all day in search of an answer, but with no success. I don't think it's possible to print JTable using it's print() method together with other components, so I will have to think of something else i guess...
    Edited by: Adalbert23 on Nov 22, 2007 2:49 PM

  • How to print (on paper) expected header and footer while printing Jtable

    Hello,
    I am printing jtable on paper using dot mtix printer.In header i want to print some name date and number like below
    Sun
    Date:12/8/20010 No.12334
    | col1 | col2 |
    | col1 | col2 |
    footer
    When i am trying to print header its Font size is very big and its in one line.How i can use expected font and expected text here.
    i am using jtable print method(which contin header and footer printing facility)
    Edited by: Ashtekar on Aug 12, 2010 5:18 AM

    I also once hoped for an easy way to modify a table's header and footer, but found no way.
    Yet it is possible.

  • Image in header of print (JTable)

    Hello,
    I have a question about printing a JTable. I use the following code which works well but I want to extend my print with a image (a logo) in the header of every page. What is the best way to achieve this?
    My second question is how I can change the font size of the header?
    Thanks for your reply.
    Regards Stefan.
    MessageFormat header = new MessageFormat("Test");
    MessageFormat footer = new MessageFormat("Page - {0}");
    try {
        if (!myTable.print(JTable.PrintMode.FIT_WIDTH
    , header, footer, true, null, true)) {
            System.err.println("User cancelled printing");
    } catch (java.awt.print.PrinterException e) {
        System.err.format("Cannot print %s%n", e.getMessage());
    }     

    The API provided by the JTable class is described as simple, and indeed it is. To obtain more complex printing, you need to use the JTable.getPrintable method and do some extra work to get the results desired.
    There are also several third party codes you can try. Do a search on google to search what you find
    ICE

  • Print - JTable with a TITLE on each page

    Hi! someone know haw can I print a MY TITLE on each page that I print ?
    ----->MY TITLE<----
    | co1 | col2 | col3 | col4 |
    |dtxxz|dtxyz|dtxyz|dtxyz|
    |dtxxz|dtxyz|dtxyz|dtxyz|
    |dtxxz|dtxyz|dtxyz|dtxyz|
    PAGE 1
    I try that :
    g.drawString("MY TITLE", 100,50);
    but the table header hide (writing over) my title
    Here is my call :
    public int print(Graphics g, PageFormat pageFormat, int pageIndex)
    throws PrinterException {
         Graphics2D g2 = (Graphics2D) g;
         g2.setColor(Color.black);
         int fontHeight = g2.getFontMetrics().getHeight();
         int fontDesent = g2.getFontMetrics().getDescent();
         pageFormat.setOrientation(pageFormat.LANDSCAPE);
         //leave room for page number
         double pageHeight = pageFormat.getImageableHeight() - fontHeight;
         double pageWidth = pageFormat.getImageableWidth();
         double tableWidth =
              (double) getCurrentTable().getColumnModel().getTotalColumnWidth();
         double scale = 1;
         if (tableWidth >= pageWidth) {
              scale = pageWidth / tableWidth;
         double headerHeightOnPage =
              getCurrentTable().getTableHeader().getHeight() * scale ;
         double tableWidthOnPage = tableWidth * scale;
         double oneRowHeight =
              (getCurrentTable().getRowHeight() + getCurrentTable().getRowMargin()) * scale;
         int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage) / oneRowHeight);
         double pageHeightForTable = oneRowHeight * numRowsOnAPage;
         int totalNumPages =
              (int) Math.ceil(((double) getCurrentTable().getRowCount()) / numRowsOnAPage);
         if (pageIndex >= totalNumPages) {
              return NO_SUCH_PAGE;
         g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
         g2.drawString(
              "Page: " + (pageIndex + 1),
              (int) pageWidth / 2 - 35,
              (int) (pageHeight + fontHeight - fontDesent));
         //bottom center
         g2.translate(0f, headerHeightOnPage);
         g2.translate(0f, -pageIndex * pageHeightForTable);
         //TODO this next line treats the last page as a full page
         g2.setClip(
              0,
              (int) (pageHeightForTable * pageIndex),
              (int) Math.ceil(tableWidthOnPage),
              (int) Math.ceil(pageHeightForTable));
         g2.scale(scale, scale);
         getCurrentTable().paint(g2);
         g2.scale(1 / scale, 1 / scale);
         g2.translate(0f, pageIndex * pageHeightForTable);
         g2.translate(0f, -headerHeightOnPage);
         g2.setClip(
              0,
              0,
              (int) Math.ceil(tableWidthOnPage),
              (int) Math.ceil(headerHeightOnPage));
         g2.scale(scale, scale);
         getCurrentTable().getTableHeader().paint(g2); //paint header at top
         return Printable.PAGE_EXISTS;
    Thanks

    //Solution-------------------------------------------------------------------------------------------------------
    // PRINT : CENTER HEADER TITLE ON EACH PAGE
    : PAGE NUMBER ON EACH PAGE
    : USE A PREVIEW WINDOW
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.awt.event.*;
    * File: PrintTable.java
    * (C) Copyright Corp. 2001 - All Rights Reserved.
    * Print a JTable data
    public class PrintTable implements Printable {
    * Insert the method's description here.
    * Creation date: (03-13-2002 13:50:41)
    * @param g java.awt.Graphics
    * @param pg java.awt.print.PageFormat
    * @param i int
    public int print(Graphics g, PageFormat pageFormat,
         int pageIndex) throws PrinterException {
         try{
              Graphics2D g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              int fontHeight = g2.getFontMetrics().getHeight();
              int fontDesent = g2.getFontMetrics().getDescent();
              // Normalize the header color
              // he title of the report is not printed if the color of the header is different of these colors
              m_table.getTableHeader().setBackground(new java.awt.Color(204,204,204));
              m_table.getTableHeader().setForeground(new java.awt.Color(0,0,0));
              //leave room for page number
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) m_table.getColumnModel().getTotalColumnWidth();
              double scale = 1;
              if (tableWidth >= pageWidth) {
                   scale = pageWidth / tableWidth;
              // Get the size of the table header
              double headerHeightOnPage = m_table.getTableHeader().getHeight() * scale;
              // Get the table size on a page
              double tableWidthOnPage = tableWidth * scale;
              // Title Height
              double titleHeightOnPage = 0;
              if( m_title != null ){
                   titleHeightOnPage = ((double)m_title.getFontMetrics(m_title.getFont()).getHeight() + 40) * scale;
              // Get size of a row
              double oneRowHeight =
                   (m_table.getRowHeight() + m_table.getRowMargin()) * scale;
              int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage - titleHeightOnPage) / oneRowHeight);
              // Get number of row in a page
              double pageHeightForTable = oneRowHeight * numRowsOnAPage;
              // Get the number of page to print
              int totalNumPages =
                   (int) Math.ceil(((double) m_table.getRowCount()) / numRowsOnAPage);
              if (pageIndex >= totalNumPages) {
                   return NO_SUCH_PAGE;
              // Print the page label at bottom center
              g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              g2.drawString(
                   "Page: " + (pageIndex + 1),
                   (int) pageWidth / 2 - 35,
                   (int) (pageHeight + fontHeight - fontDesent));
              g2.translate(0f, headerHeightOnPage + titleHeightOnPage);
              g2.translate(0f, -pageIndex * pageHeightForTable);
              //If this piece of the table is smaller than the size available,
              //clip to the appropriate bounds.
              if (pageIndex + 1 == totalNumPages) {
                   int lastRowPrinted = numRowsOnAPage * pageIndex;
                   int numRowsLeft = m_table.getRowCount() - lastRowPrinted;
                   g2.setClip(
                        0,
                        (int) (pageHeightForTable * pageIndex),
                        (int) Math.ceil(tableWidthOnPage),
                        (int) Math.ceil(oneRowHeight * numRowsLeft));
              //else clip to the entire area available.
              else {
                   g2.setClip(
                        0,
                        (int) (pageHeightForTable * pageIndex),
                        (int) Math.ceil(tableWidthOnPage),
                        (int) Math.ceil(pageHeightForTable));
              g2.scale(scale, scale);
              m_table.paint(g2);
              g2.scale(1 / scale, 1 / scale);
              g2.translate(0f, pageIndex * pageHeightForTable);
              g2.translate(0f, -headerHeightOnPage );
              g2.setClip(
                   0,
                   0,
                   (int) Math.ceil(tableWidthOnPage),
                   (int) Math.ceil(headerHeightOnPage));
              g2.scale(scale, scale);
              // Paint header at the top of the page
              m_table.getTableHeader().paint(g2);
              g2.scale(1 / scale, 1/ scale);
              g2.translate(0f, -titleHeightOnPage);
              g2.setClip(
                   0,
                   0,
                   (int) Math.ceil(tableWidthOnPage),
                   (int) Math.ceil(titleHeightOnPage));
              // Paint title
              if( m_strTitle != null ){
                   //Center
                   g2.translate((pageFormat.getImageableWidth() / 2) -
                                  (m_title.getFontMetrics(m_title.getFont()).stringWidth(m_title.getText()) / 2 ),
                                  0f );
                   g2.drawString(m_title.getText(), 0, 10);
              }else if ( m_title != null ){
                   //Center
                   g2.translate((pageFormat.getImageableWidth() / 2) -
                                  (m_title.getFontMetrics(m_title.getFont()).stringWidth(m_title.getText()) / 2 ),
                                  0f );
                   m_title.paint(g2);     
         }catch (Exception e){
              e.printStackTrace();
              return Printable.PAGE_EXISTS;
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, String title) {
         try {
              m_table = table;
              m_strTitle = title;
              m_data     = m_table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
         protected static PrintTable instance     = new PrintTable();
         public static int LANDSCAPE = PageFormat.LANDSCAPE;
         protected static TableModel m_data;
         protected static int m_maxNumPage           = 1;
         protected static String          m_strTitle = null;
         protected static JTable      m_table;
         protected static JLabel      m_title          = null;
         // Paper orientation
         public static int PORTRAIT = PageFormat.PORTRAIT;
         private final static String PREVIEW_LBL = "Aper�u avant impression...";
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table) {
         m_table = table;
         m_data      = table.getModel();
         PrinterJob prnJob = PrinterJob.getPrinterJob();
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             prnJob.defaultPage());
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table, PageFormat pf) {
         m_table = table;
         m_data      = table.getModel();
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             pf);
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table, String title) {
         m_table = table;
         m_data      = table.getModel();
         m_strTitle = title;
         m_title = new JLabel(title);
         PrinterJob prnJob = PrinterJob.getPrinterJob();
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             prnJob.defaultPage());
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table, String title, PageFormat pf) {
         m_table = table;
         m_data      = table.getModel();
         m_strTitle = title;
         m_title = new JLabel(title);
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             pf);
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table, JLabel title) {
         m_table = table;
         m_data      = table.getModel();
         m_title = title;
         PrinterJob prnJob = PrinterJob.getPrinterJob();
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             prnJob.defaultPage());
    * Insert the method's description here.
    * Creation date: (03-13-2002 10:12:41)
    public static void preview(JTable table, JLabel title, PageFormat pf) {
         m_table = table;
         m_data      = table.getModel();
         m_title = title;
         new PrintPreview(PrintTable.instance,
                             PREVIEW_LBL,
                             pf);
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, String title, PageFormat pf) {
         try {
              m_table = table;
              m_strTitle = title;
              m_data     = m_table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, pf);
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, String title, PageFormat pf, int orientation) {
         try {
              m_table = table;
              m_strTitle = title;
              m_data     = m_table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
              pf.setOrientation(orientation);
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, JLabel title) {
         try {
              m_table = table;
              m_title = title;
              m_data = table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, prnJob.defaultPage());
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, JLabel title, PageFormat pf) {
         try {
              m_table = table;
              m_title = title;
              m_data      = table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, pf);
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
    * Show a print dialog box
    * Call the method to print
    * @param JTable table : table to print
    * @param String title : title of the table
    public static void print(JTable table, JLabel title, PageFormat pf, int orientation) {
         try {
              m_table = table;
              m_title = title;
              m_data      = table.getModel();
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(PrintTable.instance, pf);
              // if the print job is cancelled
              if (!prnJob.printDialog())
                   return;
              pf.setOrientation(orientation);
              // print the table
              prnJob.print();
         } catch (PrinterException pe) {
              pe.printStackTrace();
              System.err.println("Printing error: " + pe.toString());
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.*;
    import java.awt.print.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    public class PrintPreview extends JFrame
    protected int m_wPage;
    protected int m_hPage;
    protected Printable m_target;
    protected JComboBox m_cbScale;
    protected PreviewContainer m_preview;
    private String lblBtnClose           = "Fermer";
    private String lblBtnPrint           = "Imprimer...";
    protected PageFormat m_pf;
    private String[] scales                = { "10 %", "25 %", "50 %", "100 %" };
    public PrintPreview(Printable target, String title, PageFormat pf) {
         super(title);
         setSize(600, 400);
         m_target = target;
         m_pf = pf;
         JToolBar tb = new JToolBar();
         JButton bt = new JButton(this.lblBtnPrint);
         ActionListener lst = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              try {
              // Use default printer, no dialog
              PrinterJob prnJob = PrinterJob.getPrinterJob();
              prnJob.setPrintable(m_target, m_pf);
              setCursor( Cursor.getPredefinedCursor(
                   Cursor.WAIT_CURSOR));
              prnJob.print();
              setCursor( Cursor.getPredefinedCursor(
                   Cursor.DEFAULT_CURSOR));
              dispose();
              catch (PrinterException ex) {
              ex.printStackTrace();
              System.err.println("Printing error: "+ex.toString());
         bt.addActionListener(lst);
         bt.setAlignmentY(0.5f);
         bt.setMargin(new Insets(4,6,4,6));
         tb.add(bt);
         bt = new JButton(this.lblBtnClose);
         lst = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              dispose();
         bt.addActionListener(lst);
         bt.setAlignmentY(0.5f);
         bt.setMargin(new Insets(2,6,2,6));
         tb.add(bt);
         m_cbScale = new JComboBox(scales);
         lst = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
              Thread runner = new Thread() {
              public void run() {
                   String str = m_cbScale.getSelectedItem().
                   toString();
                   if (str.endsWith("%"))
                   str = str.substring(0, str.length()-1);
                   str = str.trim();
                   int scale = 0;
                   try { scale = Integer.parseInt(str); }
                   catch (NumberFormatException ex) { return; }
                   int w = (int)(m_wPage*scale/100);
                   int h = (int)(m_hPage*scale/100);
                   Component[] comps = m_preview.getComponents();
                   for (int k=0; k<comps.length; k++) {
                   if (!(comps[k] instanceof PagePreview))
                        continue;
                   PagePreview pp = (PagePreview)comps[k];
                        pp.setScaledSize(w, h);
                   m_preview.doLayout();
                   m_preview.getParent().getParent().validate();
              runner.start();
         m_cbScale.addActionListener(lst);
         m_cbScale.setMaximumSize(m_cbScale.getPreferredSize());
         m_cbScale.setEditable(true);
         tb.addSeparator();
         tb.add(m_cbScale);
         getContentPane().add(tb, BorderLayout.NORTH);
         m_preview = new PreviewContainer();
         PrinterJob prnJob = PrinterJob.getPrinterJob();
         PageFormat pageFormat = pf;
         if (pageFormat.getHeight()==0 || pageFormat.getWidth()==0) {
         System.err.println("Unable to determine default page size");
              return;
         m_wPage = (int)(pageFormat.getWidth());
         m_hPage = (int)(pageFormat.getHeight());
         int scale = 10;
         int w = (int)(m_wPage*scale/100);
         int h = (int)(m_hPage*scale/100);
         int pageIndex = 0;
         try {
         while (true) {
              BufferedImage img = new BufferedImage(m_wPage,
              m_hPage, BufferedImage.TYPE_INT_RGB);
              Graphics g = img.getGraphics();
              g.setColor(Color.white);
              g.fillRect(0, 0, m_wPage, m_hPage);
              if (target.print(g, pageFormat, pageIndex) !=
              Printable.PAGE_EXISTS)
              break;
              PagePreview pp = new PagePreview(w, h, img);
              m_preview.add(pp);
              pageIndex++;
         catch (PrinterException e) {
         e.printStackTrace();
         System.err.println("Printing error: "+e.toString());
         JScrollPane ps = new JScrollPane(m_preview);
         getContentPane().add(ps, BorderLayout.CENTER);
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);
         setVisible(true);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    * Insert the type's description here.
    * Creation date: (03-12-2002 14:17:45)
    * @author: Alexandre Spain
    public class PreviewContainer extends JPanel {
         protected int H_GAP = 16;
         protected int V_GAP = 10;
    * PreviewContainer constructor comment.
    public PreviewContainer() {
         super();
    public void doLayout() {
         Insets ins = getInsets();
         int x = ins.left + H_GAP;
         int y = ins.top + V_GAP;
         int n = getComponentCount();
         if (n == 0)
              return;
         Component comp = getComponent(0);
         Dimension dc = comp.getPreferredSize();
         int w = dc.width;
         int h = dc.height;
         Dimension dp = getParent().getSize();
         int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
         int nRow = n/nCol;
         if (nRow*nCol < n)
              nRow++;
         int index = 0;
         for (int k = 0; k<nRow; k++) {
              for (int m = 0; m<nCol; m++) {
                   if (index >= n)
                        return;
                   comp = getComponent(index++);
                   comp.setBounds(x, y, w, h);
                   x += w+H_GAP;
              y += h+V_GAP;
              x = ins.left + H_GAP;
    public Dimension getMaximumSize() {
         return getPreferredSize();
    public Dimension getMinimumSize() {
         return getPreferredSize();
    public Dimension getPreferredSize() {
         int n = getComponentCount();
         if (n == 0)
              return new Dimension(H_GAP, V_GAP);
         Component comp = getComponent(0);
         Dimension dc = comp.getPreferredSize();
         int w = dc.width;
         int h = dc.height;
         Dimension dp = getParent().getSize();
         int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
         int nRow = n/nCol;
         if (nRow*nCol < n)
              nRow++;
         int ww = nCol*(w+H_GAP) + H_GAP;
         int hh = nRow*(h+V_GAP) + V_GAP;
         Insets ins = getInsets();
         return new Dimension(ww+ins.left+ins.right,
                                  hh+ins.top+ins.bottom);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    * Insert the type's description here.
    * Creation date: (03-12-2002 14:17:06)
    * @author: Alexandre Spain
    public class PagePreview extends JPanel {
         protected int m_w;
         protected int m_h;
         protected Image m_source;
         protected Image m_img;
    * PagePreview constructor comment.
    * @param target java.awt.print.Printable
    public PagePreview(int w, int h, Image source) {
         m_w = w;
         m_h = h;
         m_source= source;
         m_img = m_source.getScaledInstance(m_w, m_h,
              Image.SCALE_SMOOTH);
         m_img.flush();
         setBackground(Color.white);
         setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
    public Dimension getMaximumSize() {
         return getPreferredSize();
    public Dimension getMinimumSize() {
         return getPreferredSize();
    public Dimension getPreferredSize() {
         Insets ins = getInsets();
         return new Dimension(m_w+ins.left+ins.right,
                                  m_h+ins.top+ins.bottom);
    public void paint(Graphics g) {
         g.setColor(getBackground());
         g.fillRect(0, 0, getWidth(), getHeight());
         g.drawImage(m_img, 0, 0, this);
         paintBorder(g);
    public void setScaledSize(int w, int h) {
         m_w = w;
         m_h = h;
         m_img = m_source.getScaledInstance(m_w, m_h,
         Image.SCALE_SMOOTH);
         repaint();

  • Print JTable with row headers

    I am using the fancy new printing capablities in java 1.5 to print my JTable and wow is it ever slick!
    PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
    set.add(OrientationRequested.LANDSCAPE);
    this.matrixJTable.print(JTable.PrintMode.NORMAL, null, null, true, set, false);Its just that easy. Way to go sun!
    The one problem that I am encountering is that my row headers don't print. The problem is that JTables don't support row headers, you have to use a JScrollPane for that.
    I need a way to print my JTable so that the row headers show up in the printout... and hopefully still use the warm and fuzzy new printing capabilities of JTable printing in java 1.5.
    (ps/ Isn't it time to add row header support to JTables?)

    The problem is that JTables don't support row headers, you have to use a JScrollPane for that.Well technically JTable's don't really support column headers either. It is a seperate component (JTableHeader). A JTable will automatically add its table header to the table header area of a JScrollPane. (but you don't have to use a jscrollpane to see the column headers, it is just the quickest and easiest way).
    Really shouldn't be hard to implement a row header and manually add it to the scroll panes row header area or use a BorderLayout and put your row header in the WEST and put your table in the CENTER if you don't want a scroll pane.
    Of course this won't help you with your printing issue.

  • Printing JTable problem

    hi
    i have a problem in printing jtable
    after printing the box around the table only printed and the content of the table isn't
    instead there is a wight space in the box
    can any one help me

    In fact the program i'm making is for printing preview
    it's three classes i found in one of the topics , then i modified them to preview a table
    here is my code : \\ the class "TPrintPreview" needs a JTable object as an argument
    ********************************TPrintPreview.java************************************************************
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.print.PageFormat;
    import java.awt.print.Paper;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import java.text.MessageFormat;
    import javax.swing.JTable;
    import javax.swing.JTable.PrintMode;
    * @author  TAREQ145
    public class TPrintPreview extends javax.swing.JFrame {
       int m_wPage;
       int m_hPage;
        /** Creates new form TPrintPreview */
        public TPrintPreview(JTable table) {
            initComponents();
            PageFormat m_pageFormat = PrinterJob.getPrinterJob().defaultPage();//use PageDialog
            m_wPage = (int)(m_pageFormat.getWidth());
            m_hPage = (int)(m_pageFormat.getHeight());
            int scale = getScale(5);  //Scale Index = 100
            jComboBox1.setSelectedIndex(5);
            int w = (int)(m_wPage*scale/100);
            int h = (int)(m_hPage*scale/100);   
            int pageIndex = 0;
            try{
            while (true) {
                int theFirstImageWidth = table.getColumnModel().getTotalColumnWidth()+1;
                BufferedImage img = new BufferedImage(theFirstImageWidth, theFirstImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g = img.getGraphics();
                g.setColor(Color.white);
                g.fillRect(0, 0, theFirstImageWidth , theFirstImageWidth+180);//180 = height - width
                Paper p = new Paper();
                p.setImageableArea(0,0,theFirstImageWidth,theFirstImageWidth+180);
                m_pageFormat.setPaper(p);
                Printable  m_target = table.getPrintable(PrintMode.FIT_WIDTH,null,new MessageFormat("- {0} -"));
               if (m_target.print(g, m_pageFormat, pageIndex) != Printable.PAGE_EXISTS) {
                   img = null;
                   break;
                int rightOrLeftSpace = 25;
                int upOrDownSpace = 25;
                int theSecondImageWidth = theFirstImageWidth + (rightOrLeftSpace*2);
                BufferedImage img2 = new BufferedImage(theSecondImageWidth, theSecondImageWidth+180, BufferedImage.TYPE_INT_RGB); 
                Graphics g2 = img2.getGraphics();
                g2.setColor(Color.white);
                g2.fillRect(0, 0, theSecondImageWidth, theSecondImageWidth+180);
                g2.drawImage(img,rightOrLeftSpace,upOrDownSpace,null); 
                Image img3 = img2.getScaledInstance(m_wPage,m_hPage,Image.SCALE_SMOOTH);
                PagePreview pp = new PagePreview(w, h, img3);
                previewContainer1.add(pp);
                //pp = null;
                pageIndex++;
                img = null;
                g = null;
            } catch (PrinterException e)   {
              e.printStackTrace();
             System.err.println("Printing error: "+e.toString());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            previewContainer1 = new PreviewContainer();
            jButton1 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            setTitle("Print Preview");
            jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24));
            jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jLabel1.setText("Print Preview");
            jLabel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
            javax.swing.GroupLayout previewContainer1Layout = new javax.swing.GroupLayout(previewContainer1);
            previewContainer1.setLayout(previewContainer1Layout);
            previewContainer1Layout.setHorizontalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 752, Short.MAX_VALUE)
            previewContainer1Layout.setVerticalGroup(
                previewContainer1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 511, Short.MAX_VALUE)
            jScrollPane1.setViewportView(previewContainer1);
            jButton1.setText("EXIT");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %", "125 %", "150 %", "175 %", "200 %" }));
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 754, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 754, Short.MAX_VALUE))
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(183, 183, 183)
                            .addComponent(jButton1)
                            .addGap(74, 74, 74))))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 513, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(40, 40, 40)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(80, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            this.dispose();
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                          
            int scale = getScale(jComboBox1.getSelectedIndex());
                      int w = (int)(m_wPage*scale/100);
                      int h = (int)(m_hPage*scale/100);
                      Component[] comps = previewContainer1.getComponents();
                      for (int k=0; k<comps.length; k++) {
                         if (!(comps[k] instanceof PagePreview)) continue;
                         PagePreview pp = (PagePreview)comps[k];
                         pp.setScaledSize(w, h);
                      previewContainer1.doLayout();
                      getContentPane().validate();
        private int getScale(int scaleIndex) {
          int scale = 10;
          String[] scales = { "10 %", "25 %", "30 %", "50 %", "75 %", "100 %" , "125 %","150 %","175 %","200 %"};
          if (scaleIndex>-1 && scaleIndex<scales.length) {
             String str = scales[scaleIndex];
             if (str.endsWith("%"))str = str.substring(0, str.length()-1);
             str = str.trim();
             try { scale = Integer.parseInt(str); }
             catch (NumberFormatException ex) { ex.printStackTrace();}
          return scale;
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private PreviewContainer previewContainer1;
        // End of variables declaration                  
    ********************************PreviewContainer.java************************************************************
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PreviewContainer.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:20 &#1605;
    * @author  TAREQ145
    public class PreviewContainer extends JPanel {
        protected int H_GAP = 16;
        protected int V_GAP = 10;
        /** Creates new form BeanForm */
        public PreviewContainer() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
          public Dimension getPreferredSize() {
             int n = getComponentCount();
             if (n == 0) return new Dimension(H_GAP, V_GAP);
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width - H_GAP) / (dc.width + H_GAP), 1);
             int nRow = n / nCol;
             if ((nRow * nCol) < n) nRow++;
             int ww = nCol * (dc.width + H_GAP) + H_GAP;
             int hh = nRow * (dc.height + V_GAP) + V_GAP;
             Insets ins = getInsets();
             return new Dimension(ww+ins.left+ins.right, hh+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void doLayout() {
             Insets ins = getInsets();
             int x = ins.left + H_GAP;
             int y = ins.top + V_GAP;
             int n = getComponentCount();
             if (n == 0) return;
             Component comp = getComponent(0);
             Dimension dc = comp.getPreferredSize();
             int w = dc.width;
             int h = dc.height;
    //fl+ 03.09.2003
             if (getParent() == null) return;
    //fl-        
             Dimension dp = getParent().getSize();
             int nCol = Math.max((dp.width-H_GAP)/(w+H_GAP), 1);
             int nRow = n/nCol;
             if (nRow*nCol < n) nRow++;
             int index = 0;
             for (int k = 0; k<nRow; k++) {
                for (int m = 0; m<nCol; m++) {
                   if (index >= n) return;
                   comp = getComponent(index++);
                   comp.setBounds(x, y, w, h);
                   x += w+H_GAP;
                y += h+V_GAP;
                x = ins.left + H_GAP;
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    ******************************PagePreview.java***********************************************************************************
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Insets;
    import javax.swing.JPanel;
    * PagePreview.java
    * Created on 04 &#1603;&#1575;&#1606;&#1608;&#1606; &#1575;&#1604;&#1579;&#1575;&#1606;&#1610;, 2008, 10:25 &#1605;
    import javax.swing.border.MatteBorder;
    * @author  TAREQ145
    public class PagePreview extends JPanel {
         protected int m_w;
         protected int m_h;
         protected Image m_source;
         protected Image m_img;
        /** Creates new form BeanForm */
        public PagePreview() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
        }// </editor-fold>                       
        public PagePreview(int w, int h, Image source) {
             m_w = w;
             m_h = h;
             m_source = source;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             m_img.flush();
             setBackground(Color.white);
             setBorder(new MatteBorder(1, 1, 2, 2, Color.black));
          public void setScaledSize(int w, int h) {
             m_w = w;
             m_h = h;
             m_img = m_source.getScaledInstance(m_w, m_h, Image.SCALE_SMOOTH);
             repaint();
          public Dimension getPreferredSize() {
             Insets ins = getInsets();
             return new Dimension(m_w+ins.left+ins.right,
                m_h+ins.top+ins.bottom);
          public Dimension getMaximumSize() {
             return getPreferredSize();
          public Dimension getMinimumSize() {
             return getPreferredSize();
          public void paint(Graphics g) {
             g.setColor(getBackground());
             g.fillRect(0, 0, getWidth(), getHeight());
             g.drawImage(m_img, 0, 0, this);
             paintBorder(g);
        // Variables declaration - do not modify                    
        // End of variables declaration                  
    }please help me
    thankz

  • Print JTable with column heading

    Hi,
    I'm very new to this JTable. I'm try to print a Jtable using the print() function (from JDK 1.5)
    JTable.print(JTable.PrintMode.FIT_WIDTH, new MessageFormat(
    _tabledata.getTitle() ),
    new MessageFormat("Page {0,number}"));
    The problem I have is that some time it print and other time it doens't print. Also, if it doesn't print, then the program become very slow or not respond. Is that the probelm with the new JDK or am I doing something wrong?
    Thanks for you help.

    Don't rely on JTable.print() methods too much.
    Sadly Sun didn't think anyone would need to print anything from java so support was added late and half heartedly (programmers hate printing stuff)
    If you are new to java you need to focus on something simpler than printing documents; unfortunatly printing is a tedious burdonsome task for experreineced developers
    for example: learn how to output your data from a table into an HTML formate/file; you can build beautiful reports/printouts easily and view them in java components easily but you will probably want to print them from a browser.
    Even if you find a class or two to help with your printing efforts on the net you will find you need to know many other generic complicated aspects of java to continue
    Sean

  • Print Jtable with multiline header?

    i want to print jtable with multi-lines header and footer
    using the print function that takes MessageFormat as header and footer
    i used MessageFormat header = new MessageFormat("hello\r\nworld");and i used '\n' only
    but it was printed all in the same line
    thnx in advance

    You can try something on the below lines. Set your custom renderer for the tableheader.
    public class MultiLineHeaderRenderer extends DefaultTableCellRenderer{
            public Component getTableCellRendererComponent(JTable table, Object value,
                             boolean isSelected, boolean hasFocus, int row, int column) {
                         JLabel label = (JLabel) super.getTableCellRendererComponent( table,  value,
                              isSelected,  hasFocus,  row,  column);
                        label.setText("<html>a<br>b</html>");
                        return label;
        }Not the best way to do it. And might need to some modifications too to set the font position etc.

  • Printing JTable SOS

    Hi , Iknow... this is an question very request... but... What can say . I NEED HEL P
    I need printing JTABLE LANDSCAPE here my code example ...
    Thank you.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import com.sun.java.swing.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.standard.OrientationRequested;
    import javax.swing.*;
    public class printpanel extends JPanel implements ActionListener, Printable {
    public printpanel() {
         setBackground(Color.white);
    JButton b = new JButton("MyButton");
    b.addActionListener(this);
    add(b);
         JLabel tit = new JLabel ("Liquidaci�n M�dico");
              tit.setFont( new Font( "Helvetica",Font.BOLD,16 ) );
              tit.setForeground(Color.black);
              setBackground(Color.white);
              add(tit);     
    //array bidimencional de objetos con los datos de la tabla
    final Object[][] data = {
    {"Mary", "Campione", "Esquiar", new Integer(5), new Boolean(false)},
    {"Lhucas", "Huml", "Patinar", new Integer(3), new Boolean(true)},
    {"Kathya", "Walrath", "Escalar", new Integer(2), new Boolean(false)},
    {"Marcus", "Andrews", "Correr", new Integer(7), new Boolean(true)},
    {"Angela", "Lalth", "Nadar", new Integer(4), new Boolean(false)}
    //array de String's con los t�tulos de las columnas
    final String[] columnNames = {"Nombre", "Apellido", "Pasatiempo",
    "A�os de Practica", "Soltero(a)"};
    //se crea la Tabla
    final JTable table = new JTable(data, columnNames);
    // table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setSelectionBackground( Color.red );
    //Creamos un JscrollPane y le agregamos la JTable
    final JScrollPane scrollPane = new JScrollPane(table);
         add(scrollPane);
    public void actionPerformed(ActionEvent e) {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    PageFormat a = new PageFormat();
    try { printJob.print(); } catch (Exception PrintException) { }
    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2d= (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    Font f = new Font("Monospaced",Font.PLAIN,12);
         g2d.setFont (f);
         paint (g);
    return Printable.PAGE_EXISTS;
    public static void main(String s[]) {
         WindowListener l = new WindowAdapter() {
         public void windowClosing(WindowEvent e) {System.exit(0);}
         Frame f = new Frame("Imprimir");
         f.addWindowListener(l);
         f.add("Center", new printpanel());
         //f.pack();
         f.setSize(new Dimension(500,300));
         f.show();
    }

    Hai!,
    I am posting this code for the request i received from the mfwjava-person by mail. The below modified code works well.
    I Used ORACLE ODBC* since it only supports more query features of sql statements and your select *... statement works well in this only. I didn't checked the print - out. But our senior Mr.URHAND checked it(Thank him).
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.geom.Rectangle2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.print.attribute.*;
    import javax.print.*;
    import javax.print.attribute.standard.*;
    import javax.print.attribute.standard.MediaSize;
    import java.sql.Connection;
    import java.sql.*;
    import java.text.MessageFormat;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class Grafica extends JPanel implements ActionListener {
    JTable table=new JTable();
    public static JScrollPane scrollPane;
    public Grafica() {
    JButton b = new JButton("Imprimir");
    b.addActionListener(this);
    add(b);
    JLabel tit = new JLabel("Liquidaci�n M�dico");
    tit.setFont( new Font( "Helvetica",Font.BOLD,16 ) );
    tit.setForeground(Color.black);
    setBackground(Color.white);
    add(tit);
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:Sego", "scott", "tiger");
    DriverManager.setLogStream(System.out);
    Statement statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    ResultSet rs = statement.executeQuery("SELECT Medico_opera,Descip_Item,Codigo_estudio,Count(Descip_Item),Sum(Liquid_opera) FROM Datos Group By Medico_opera,Descip_Item,Codigo_estudio ");
    rs=statement.getResultSet();
    String[] columnas = {"M�dico","Descripci�n Item","Codigo nr.","Total de Items","Total M�dico Op."};
    JTable table =rsInTable(rs);
    scrollPane = new JScrollPane(table);
    add(scrollPane);
    statement.close();
    con.close();
    } catch (SQLException sqle) {
    sqle.printStackTrace();
    } catch (Exception ed) {
    ed.printStackTrace();
    public void actionPerformed(ActionEvent e) {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable( new TableReport(table,
    new MessageFormat("Liquidaci�n M�dico"), null) );
    try{
    PrinterJob prnJob = PrinterJob.getPrinterJob();
         PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
         //aset.add(new Copies(2));
         //aset.add(new MediaSize.getMediaSizeForName(MediaSizeName.ISO_A4));
    //aset.add(MediaName.ISO_A4_WHITE);
         aset.add(MediaSizeName.ISO_A4);
         aset.add(Sides.ONE_SIDED);
         aset.add(OrientationRequested.LANDSCAPE);//------>HERE IT IS
         if (!prnJob.printDialog(aset))return;
         //aset.add(MediaName.ISO_A4_TRANSPARENT);
    setCursor( Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    prnJob.print();
    setCursor( Cursor.getPredefinedCursor(
    Cursor.DEFAULT_CURSOR));
    }catch (Exception PrintException) {}
    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
    if (pi >= 1) {
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2d= (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    Font f = new Font("Monospaced",Font.PLAIN,12);
    g2d.setFont(f);
    paint(g);
    return Printable.PAGE_EXISTS;
    public static void main(String s[]) {
    WindowListener l = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    Frame f = new Frame("Imprimir");
    f.addWindowListener(l);
    f.add("Center", new Grafica());
    f.setSize(new Dimension(500,300));
    f.show();
    public JTable rsInTable(ResultSet rs)throws SQLException{
    JTable table;
    boolean moreRecords=rs.next();
    table=new JTable(0,0);
    Vector colh=new Vector();
    Vector rows=new Vector();
    try{
    ResultSetMetaData rsmd=rs.getMetaData();
    for(int i=1;i<=rsmd.getColumnCount();++i)
    colh.addElement(rsmd.getColumnName(i));
    System.out.println(String.valueOf(rs.getRow()));
    while(rs.next()){
    rows.addElement(getNextRow(rs,rsmd));
    table=new JTable(rows,colh);
    catch(SQLException e2)
    e2.printStackTrace();
    if(!moreRecords)
    return table;
    return table;
    private Vector getNextRow(ResultSet rs,ResultSetMetaData rsmd)throws SQLException
    Vector crow=new Vector();
    for(int i=1;i<=rsmd.getColumnCount();++i)
    switch(rsmd.getColumnType(i))
    case Types.VARCHAR:
    crow.addElement(rs.getString(i));
    break;
    case Types.INTEGER:
    crow.addElement(new Long(rs.getLong(i)));
    break;
    case Types.DOUBLE:
    crow.addElement(new Double(rs.getDouble(i)));
    break;//----> HERE U ADD OTHER TYPES - U NEED?
    default:
    crow.addElement(new String(rs.getString(i)));
    System.out.println("type was: "+rsmd.getColumnTypeName(i));
    break;
    return crow;
    class TableReport implements Printable {
    private JTable table;
    private JTableHeader header;
    private TableColumnModel colModel;
    private int totalColWidth;
    private MessageFormat headerFormat;
    private MessageFormat footerFormat;
    private int last = -1;
    private int row = 0;
    private int col = 0;
    private final Rectangle clip = new Rectangle(0, 0, 0, 0);
    private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
    private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
    private static final int H_F_SPACE = 8;
    private static final float HEADER_FONT_SIZE = 18.0f;
    private static final float FOOTER_FONT_SIZE = 12.0f;
    private Font headerFont;
    private Font footerFont;
    public TableReport(JTable table,
    MessageFormat headerFormat,
    MessageFormat footerFormat) {
    this.table = table;
    header = table.getTableHeader();
    colModel = table.getColumnModel();
    totalColWidth = colModel.getTotalColumnWidth();
    if (header != null) {
    hclip.height = header.getHeight();
    this.headerFormat = headerFormat;
    this.footerFormat = footerFormat;
    headerFont = table.getFont().deriveFont(Font.BOLD,
    HEADER_FONT_SIZE);
    footerFont = table.getFont().deriveFont(Font.PLAIN,
    FOOTER_FONT_SIZE);
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
    throws PrinterException {
    final int imgWidth = (int)pageFormat.getImageableWidth();
    final int imgHeight = (int)pageFormat.getImageableHeight();
    if (imgWidth <= 0) {
    throw new PrinterException("Width of printable area is too small.");
    Object[] pageNumber = new Object[]{new Integer(pageIndex + 1)};
    String headerText = null;
    if (headerFormat != null) {
    headerText = headerFormat.format(pageNumber);
    String footerText = null;
    if (footerFormat != null) {
    footerText = footerFormat.format(pageNumber);
    Rectangle2D hRect = null;
    Rectangle2D fRect = null;
    int headerTextSpace = 0;
    int footerTextSpace = 0;
    int availableSpace = imgHeight;
    if (headerText != null) {
    graphics.setFont(headerFont);
    hRect = graphics.getFontMetrics().getStringBounds(headerText,
    graphics);
    headerTextSpace = (int)Math.ceil(hRect.getHeight());
    availableSpace -= headerTextSpace + H_F_SPACE;
    if (footerText != null) {
    graphics.setFont(footerFont);
    fRect = graphics.getFontMetrics().getStringBounds(footerText,
    graphics);
    footerTextSpace = (int)Math.ceil(fRect.getHeight());
    availableSpace -= footerTextSpace + H_F_SPACE;
    if (availableSpace <= 0) {
    throw new PrinterException("Height of printable area is too small.");
    double sf = 1.0D;
    if ( totalColWidth > imgWidth) {
    sf = (double)imgWidth / (double)totalColWidth;
    while (last < pageIndex) {
    if (row >= table.getRowCount() && col == 0) {
    return NO_SUCH_PAGE;
    int scaledWidth = (int)(imgWidth / sf);
    int scaledHeight = (int)((availableSpace - hclip.height) / sf);
    findNextClip(scaledWidth, scaledHeight);
    last++;
    Graphics2D g2d = (Graphics2D)graphics;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    AffineTransform oldTrans;
    if (footerText != null) {
    oldTrans = g2d.getTransform();
    g2d.translate(0, imgHeight - footerTextSpace);
    printText(g2d, footerText, fRect, footerFont, imgWidth);
    g2d.setTransform(oldTrans);
    if (headerText != null) {
    printText(g2d, headerText, hRect, headerFont, imgWidth);
    g2d.translate(0, headerTextSpace + H_F_SPACE);
    tempRect.x = 0;
    tempRect.y = 0;
    tempRect.width = imgWidth;
    tempRect.height = availableSpace;
    g2d.clip(tempRect);
    if (sf != 1.0D) {
    g2d.scale(sf, sf);
    } else {
    int diff = (imgWidth - clip.width) / 2;
    g2d.translate(diff, 0);
    oldTrans = g2d.getTransform();
    Shape oldClip = g2d.getClip();
    if (header != null) {
    hclip.x = clip.x;
    hclip.width = clip.width;
    g2d.translate(-hclip.x, 0);
    g2d.clip(hclip);
    header.print(g2d);
    g2d.setTransform(oldTrans);
    g2d.setClip(oldClip);
    g2d.translate(0, hclip.height);
    g2d.translate(-clip.x, -clip.y);
    g2d.clip(clip);
    table.print(g2d);
    g2d.setTransform(oldTrans);
    g2d.setClip(oldClip);
    g2d.setColor(Color.BLACK);
    g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
    return PAGE_EXISTS;
    private void printText(Graphics2D g2d,
    String text,
    Rectangle2D rect,
    Font font,
    int imgWidth) {
    int tx;
    if (rect.getWidth() < imgWidth) {
    tx = (int)((imgWidth - rect.getWidth()) / 2);
    } else if (table.getComponentOrientation().isLeftToRight()) {
    tx = 0;
    } else {
    tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
    int ty = (int)Math.ceil(Math.abs(rect.getY()));
    g2d.setColor(Color.BLACK);
    g2d.setFont(font);
    g2d.drawString(text, tx, ty);
    private void findNextClip(int pw, int ph) {
    final boolean ltr = table.getComponentOrientation().isLeftToRight();
    if (col == 0) {
    if (ltr) {
    clip.x = 0;
    } else {
    clip.x = totalColWidth;
    clip.y += clip.height;
    clip.width = 0;
    clip.height = 0;
    int rowCount = table.getRowCount();
    int rowHeight = table.getRowHeight(row);
    do {
    clip.height += rowHeight;
    if (++row >= rowCount) {
    break;
    rowHeight = table.getRowHeight(row);
    } while (clip.height + rowHeight <= ph);
    clip.x = 0;
    clip.width = totalColWidth;
    * ALWAYS POST IN THIS FORUMS
    *I ALWAYS LIKE TO REPLY IN THIS FORUM.SO PLEASE!!!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem printing JTable

    here is the code
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    // Java extension packages
    import javax.swing.*;
    import javax.swing.table.*;
    class DisplayQueryResultsDOD extends JFrame implements Printable,ActionListener
    ResultSetTableModelDOD tableModel;
    JTextArea queryArea;
    JTable resultTable;
    // create ResultSetTableModel and GUI
    DisplayQueryResultsDOD()
    super( "Displaying Query Results" );
    // Cloudscape database driver class name
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    // URL to connect to books database
    String url = "jdbc:odbc:MyDataSource";
    // query to select entire authors table
    String query = "SELECT * FROM person";
    // create ResultSetTableModel and display database table
         try
    // create TableModel for results of query
    // SELECT * FROM authors
              tableModel =
              new ResultSetTableModelDOD( driver, url, query );
    // set up JTextArea in which user types queries
              queryArea = new JTextArea( query, 3, 100 );
              queryArea.setWrapStyleWord( true );
              queryArea.setLineWrap( true );
              JScrollPane scrollPane = new JScrollPane( queryArea,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER );
    // set up JButton for submitting queries
              JButton submitButton = new JButton( "Submit Query" );
    // create Box to manage placement of queryArea and
    Box box = Box.createHorizontalBox();
              box.add( scrollPane );
              box.add( submitButton );
    // create JTable delegate for tableModel
              JTable resultTable = new JTable( tableModel );
    // place GUI components on content pane
              Container c = getContentPane();
              c.add( box, BorderLayout.NORTH );
              c.add( new JScrollPane( resultTable ),
              BorderLayout.CENTER );
    // create event listener for submitButton
              submitButton.addActionListener(
         new ActionListener()
         public void actionPerformed( ActionEvent e )
    // perform a new query
         try
              tableModel.setQuery( queryArea.getText() );
    // catch SQLExceptions that occur when
    // performing a new query
         catch ( SQLException sqlException )
              JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error",JOptionPane.ERROR_MESSAGE );
    } // end actionPerformed
    } // end ActionListener inner class
    // set window size and display window
    JMenuBar menuBar = new JMenuBar();
         JMenu filemenu= new JMenu("File");
         JMenu submenux=new JMenu("Open");
         JMenuItem np=new JMenuItem("Launch Panel");
         submenux.add(np);
         //openmenuitem.addActionListener(this);
         submenux.setActionCommand("Open");
         submenux.setMnemonic('O');
         filemenu.add(submenux);
         menuBar.add(filemenu);
         JMenuItem printItem = new JMenuItem("Print");
         printItem.setMnemonic('P');
         filemenu.add(printItem);
         JMenuItem ExitItem = new JMenuItem("Exit");
    ExitItem.setMnemonic('x');
         filemenu.add(ExitItem);
         JMenu viewmenu=new JMenu("View");
         JMenuItem repItem=new JMenuItem("Reports");
         JMenu submenu=new JMenu("sort by");
         submenu.add(new JMenuItem("Marital Status"));
    submenu.add(new JMenuItem("Rank"));
         submenu.add(new JMenuItem("Tribe"));
         submenu.add(new JMenuItem("Educational Level"));
         viewmenu.add(submenu);
         menuBar.add(viewmenu);
         setJMenuBar(menuBar);
    printItem.addActionListener(this);
         ExitItem.addActionListener
         new ActionListener()
    public void actionPerformed(ActionEvent ae)
    System.exit(0);
    setSize( 1500,900);
    // setVisible( true );
    } // end try
    // catch ClassNotFoundException thrown by
    // ResultSetTableModel if database driver not found
         catch ( ClassNotFoundException classNotFound )
         JOptionPane.showMessageDialog( null,"Cloudscape driver not found", "Driver not found",JOptionPane.ERROR_MESSAGE );
              System.exit( 1 ); // terminate application
    // catch SQLException thrown by ResultSetTableModel
    // if problems occur while setting up database
    // connection and querying database
         catch ( SQLException sqlException )
         JOptionPane.showMessageDialog( null,sqlException.toString(),"Database error", JOptionPane.ERROR_MESSAGE );
         System.exit( 1 ); // terminate application
    } // end DisplayQueryResults constructor
         public void actionPerformed(ActionEvent e)
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try
    printJob.print();
    catch (Exception ex)
    ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int page) throws
    PrinterException {
    if (page > 0) { /* We have only one page, and 'page' is zero-based */
    return NO_SUCH_PAGE;
    /* User (0,0) is typically outside the imageable area, so we must
    * translate by the X and Y values in the PageFormat to avoid clipping
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());
    /* Now print the window and its visible contents */
    resultTable.printAll(g);
    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
    // execute application
    public static void main( String args[] )
    DisplayQueryResultsDOD app = new DisplayQueryResultsDOD();
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    } // end class DisplayQueryResults
    I get an exception
    pls help

    I included this statement only to check if it would print or not, because before that I tried printing the table without setting the size. Anyway, when I tried the same code under Windows it worked fine. Talking about platform independent...:-)

  • How to print Jtable values in one A4 size paper

    Hi,
    i am having JPanel , this panel have Jtbale, Jtextfield, Jlable, i search the code for Printing Jpanel, its work fine and print whole JPanel including, jtable, textbox, everything.
    my Jtable have Scroll bar to see all the values in the table,my problem is when i was print the JPanel the Jtable print only the display values in Jtable, cannot print all the values from Jtable,(eg. Jtable have 50 rows, screen display 20 rows only, move the scrollbar to see remaining,) .
    i want to print 50 rows how to print the values anyone can help me
    thanks in advance.

    Duplicate post. Mods please do your duty.

  • Print JTable with Multiple pages and rows

    I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
    1) To Print Multiple pages
    2) To wrap lines that is too long for the column
    3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
    4) To align the numbers to the right and center column headings
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    public class Report implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame frame;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public Report()
              frame = new JFrame("Sales Report");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              final String[] headers =
                   "ID",
                   "Description",
                   "open price",
                   "latest price",
                   "End Date",
                   "Quantity"
              int count = 0;
              final Object[][] data =
                   {new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
              TableModel dataModel = new AbstractTableModel()
                   public int getColumnCount() { return headers.length; }
                   public int getRowCount() { return data.length;}
                   public Object getValueAt(int row, int col)
                        return data[row][col];
                   public String getColumnName(int column)
                        return headers[column];
                   public Class getColumnClass(int col)
                        return getValueAt(0,col).getClass();
                   public boolean isCellEditable(int row, int col)
                        return (col==1);
                   public void setValueAt(Object aValue, int row, int column)
                        data[row][column] = aValue;
              tableView = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(tableView);
              scrollpane.setPreferredSize(new Dimension(500, 80));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
              frame.pack();
              JButton printButton= new JButton();
              printButton.setText("print me!");
              frame.getContentPane().add(BorderLayout.SOUTH,printButton);
              // for faster printing turn double buffering off
              RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
              printButton.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        doPrint();
              frame.setVisible(true);
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 10);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
          * We can't guarantee that the same amount of rows will be displayed on each page,
          * the row heights are dynamic and may wrap onto 2 or more lines.
          * Thus we need to calculate the height of each row and then test how may rows
          * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = tableView.getValueAt(i, j).toString();
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
          * Print the headers or a row from the table to the graphics context
          * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = obj.toString();
                   else
                        align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
                             pageFormat.getImageableY() + pageFormat.getImageableWidth(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public static void main(String[] args)
              new Report();
    }

    Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    import java.math.*;
    public class PrintJTable implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame m_parent;
         private String m_title;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public PrintJTable(JFrame parent, JTable table)
              m_parent = parent;
              tableView = table;
              doPrint();
         public PrintJTable(JFrame parent, String title, JTable table)
              m_parent = parent;
              m_title = title;
              tableView = table;
              doPrint();
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 8);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              double test = 0;
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
                   test += columnWidths;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   g2.drawString(m_title,
                                       (int)(pageFormat.getImageableX()),
                                       next_row);
                   Color current_color = g2.getColor();
                   g2.setColor(Color.lightGray);
                   int y = next_row + fontMetrics.getDescent();
                   g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                                  y,
                                  (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                                  y));
                   g2.setColor(current_color);
                   next_row += fontMetrics.getHeight();
              next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
         * We can't guarantee that the same amount of rows will be displayed on each page,
         * the row heights are dynamic and may wrap onto 2 or more lines.
         * Thus we need to calculate the height of each row and then test how may rows
         * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              headerHeight = 0;
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   headerHeight = fontMetrics.getHeight();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = formatObject(tableView.getValueAt(i, j));
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
         * Print the headers or a row from the table to the graphics context
         * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = formatObject(obj);
                   else
                        //align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              Color current_color = g2.getColor();
              g2.setColor(Color.lightGray);
              int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             y,
                             (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                             y));
              g2.setColor(current_color);
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public String formatObject(Object obj)
              String value = (obj == null) ? "" : obj.toString();
              return value;

  • Print jTable with a header and footer panel

    Hi Folks,
    I'm currently at a sticking point in a project I'm playing around with. I have a data set of around 300 objects that i'd like printed out in a table. Now, I've gotten the display part down without a hitch but printing the data as well as a header panel and footer panel has been eluding me. I'd basically like something like this...
    Name: some name Order date: some date
    Address: some address Shipped To: some address
    somewhere Some city, some state, etc
    in some city
    Date | Title | Etc | Etc | Etc
    date1 title1 5 $3.00 $15.00
    date1 title1 5 $3.00 $15.00
    date2 title1 5 $3.00 $15.00
    date2 title1 5 $3.00 $15.00
    Total purchases: $60.00
    Total Items: 20
    # of Orders: 2
    Am I barking up the wrong tree by making the first and third sections panels and the second section a table? If not, how the heck do I accomplish this? Most of the time the table has been multiple pages as well - I only need section one on the first page and section three on the last page, but whatever is easiest really.
    My current approach has been basically to make a custom printables, print the first section, figure out how high it was, print the second section and hope for the best, but the third would never show up because it'd never go over two pages.
    Any help would be very much appreciated.
    Thanks,
    Stephen
    Edited by: stephenliberty on May 7, 2009 9:11 AM - more specific subject

    I suppose as a quick update, this is as far as I've gotten and will likely get-
    public class PrintForm extends JFrame implements Printable{
        JComponent headerPanelForPrint;
        JComponent footerPanelForPrint;
        JTable dataTableForPrint;
        public void setPieces(JComponent header, JTable table, JComponent footer){
            this.headerPanelForPrint = header;
            this.footerPanelForPrint = footer;
            this.dataTableForPrint = table;
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
            TableFormat tableFormat;
            if(pageIndex>0){
                tableFormat = new TableFormat(0, footerPanelForPrint.getHeight());
            } else {
                headerPanelForPrint.printAll(graphics);
                tableFormat = new TableFormat(headerPanelForPrint.getHeight(), footerPanelForPrint.getHeight());
            MessageFormat footer = new MessageFormat("Page - {0}");
            Printable table = dataTableForPrint.getPrintable(PrintMode.FIT_WIDTH, null, footer);
            int printme = table.print(graphics, tableFormat, pageIndex);
            if(printme == table.NO_SUCH_PAGE){ return table.NO_SUCH_PAGE; }
            return Printable.PAGE_EXISTS;
    class TableFormat extends PageFormat {
        double footerHeight;
        double headerHeight;
        public TableFormat(double headerHeight, double footerHeight){
            this.headerHeight = headerHeight;
            this.footerHeight = footerHeight;
        @Override
        public double getImageableHeight() {
            return super.getImageableHeight() - ( this.footerHeight + this.headerHeight );
        @Override
        public double getHeight() {
            return super.getImageableHeight() - ( this.footerHeight + this.headerHeight);
        @Override
        public double getImageableX() {
            return 0;
        @Override
        public double getImageableY() {
            return this.headerHeight;
    }It works very well with just a header and the table, but I still have not been able to get a footer to show up in the appropriate spot or (preferably) on the last page.
    Edited by: stephenliberty on May 8, 2009 12:29 PM

  • Problem in Printing jtable swing component using dot martix Epson printer

    Hello,
         I am devoloping desktop aplication using swing.In which i want to prit jtable on paper using dot matrix printer.
    It works well if i am not chnging the font.But if i changed the font (to my local language or any any other language)
    the printing text in table gets Blur (Characters in the text get ovewrites to each other and it become hard to recognize).
    Please help me in this problem.I am trying this from more than two days but not yet found the solution.
    Thank you,
    Dattatray

    Joerg22 wrote:
    Windows allows to change the keyboard to Hindi, but not to Marathi.
    But I wonder why you are changing the focus. The problem arose when you were setting a particular font. So the first question is: Can you do without that font? Meaning: are the Devanagari characters an option?No Devanagari characters are not option.I have to use Marathi language in my application for displaying to the user and taking value from user.See perblem come into picture when i am using setFont method.i did one expriment using characters 0900-097F.For one jtext field i have set text as "\u0937\u0937\0937".In gui i saw the corresponding marathi characters for it (here i did not used any set font method).Also after printuing that on paper i saw marathi text.As i mentioned in previous post i was not able to use "\u0937\u0937\0937" this in table.It might be some mistake in string formation.But i am sure it will work.Only need to check how to form string.
    In this case Only problem is that how to take input from user.As user will not gonna input "\u0900".He will laways enter abcd....I have to interprete them into unicode.Please correct me if i am thinking wrong.
    I will try by changing the language of keyboard to hindi and get back.
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM

  • Printing JTable after turning off double buffering causing repaint problems

    I've followed all the instructions to speed up a print job in java by turning off double buffering temporarily by using the following call before calling paint() on the component...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(false);
    ... and then turning it back on afterwards...
    RepaintManager.currentManager(printTable).setDoubleBufferingEnabled(true);
    but the problem is that if it is a long print job, then the rest of the application (including other JTables) isn't repainting properly at all. I have the printing going on in a separate thread since I don't think it's acceptable UI practices to force the user to wait until a print job finishes before they can proceed with using their application. I've tried controlling the double buffering at the JPanel level as well, but it always affects the entire application until the print spooling is complete.
    Does anyone have any suggestions to solve this annoying SWING printing problem?
    Thanks,
    - Tony

    When you post code, make sure and put it between code
    tags, so it looks good:
    public static void main(String[] args) {
    System.out.println("Doesn't this look great?");
        public int print(Graphics g, PageFormat pf, int pageIndex) {
            System.out.println( "Calling print(g,pf,pageIndex) method" );
            int response = NO_SUCH_PAGE;
            Graphics2D g2 = (Graphics2D) g;
    // for faster printing, turn off double buffering
            disableDoubleBuffering(componentToBePrinted);
            Dimension d = componentToBePrinted.getSize(); //get size of document
            double panelWidth = d.width; //width in pixels
            double panelHeight = d.height; //height in pixels
            double pageHeight = pf.getImageableHeight(); //height of printer page
            double pageWidth = pf.getImageableWidth(); //width of printer page
            double scale = pageWidth / panelWidth;
            int totalNumPages = (int) Math.ceil(scale * panelHeight / pageHeight);
    // make sure not print empty pages
            if (pageIndex >= totalNumPages) {
                response = NO_SUCH_PAGE;
            } else {
    // shift Graphic to line up with beginning of print-imageable region
                g2.translate(pf.getImageableX(), pf.getImageableY());
    // shift Graphic to line up with beginning of next page to print
                g2.translate(0f, -pageIndex * pageHeight);
    // scale the page so the width fits...
                g2.scale(scale, scale);
                componentToBePrinted.paint(g2); //repaint the page for printing
                enableDoubleBuffering(componentToBePrinted);
                response = Printable.PAGE_EXISTS;
            return response;
        }

Maybe you are looking for

  • Weblogic Server 6.1 in Linux.

    when I try to start the server It's giving the following error. Please suggest. The WebLogic Server did not start up properly. Exception raised: weblogic.management.configuration.ConfigurationException: undefined mbean reference: Targets at weblogic.

  • How to retrive an Email ID from Microsoft Outlook in Java Programming ?

    Hi, Requirement : How would I get the Email lD from Outlook. I am developing an application where I receive a mail from it in that mail I have two Button One is "Approve" and other is "Reject". On each button I had written the separate code.Now I had

  • Google Contact Synchroniz​ation Issue

    When I configure a new gmail account on my device 8520 (OS 5.0.0.681) and choose contact sync option it works fine for few days but after that it stops. In options Wireless Synchronization status shows "Not Available" which I can not change also as i

  • Scripting for error messages

    Hi, 1.On a selection-screen with four select -options as s_vbeln,s_vkorg,s_vtweg,s_spart. I need to validate and write a error message ' enter atleast one field' if it is executed without any values. 2.Also validation should be done that the entered

  • There is no content on my iPod touch when it is connected to my computer.  The computer recognizes the iPod.

    When I connect my iPod Touch to my computer, and iTunes opens, no content (audiobooks) shows.  My iPod is recognized by my computer. How do I make the iPod content appear in iTunes?