How to Print entire Jtable

hi
I have used Jtable.print() command to print the JTAble but problem is that it is printing only that data which is visible row wise i.e.
if in a row one column's data is shown like
nam...
then it is printing like that only
i want to know how to print all data irrespective of how it is viewable on screen in table
please help me out
its urgent
thanks

package table;
* PrintTableDemo.java
import java.awt.*;
import java.awt.event.*;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.table.*;
public class PrintTableDemo extends JFrame {
    private JButton btPrint;
    private JTable table;
    private JTable tableToPrint;
    public PrintTableDemo() {
        super("PrintTableDemo");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(190,150);
        setLocationRelativeTo(null);
        table = new JTable();
        btPrint = new JButton();
        table.setModel(new DefaultTableModel(
            new Object [][] {{"this should print entirely", null}},
            new String [] {"Title 1", "Title 2"}
            Class[] types = new Class [] {String.class, String.class};
            boolean[] canEdit = new boolean [] {false, false};
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
        getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
        btPrint.setText("Print...");
        btPrint.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent evt) {
                btPrintActionPerformed(evt);
        getContentPane().add(btPrint, BorderLayout.NORTH);
    private void btPrintActionPerformed(final ActionEvent evt) {
        tableToPrint = new JTable(table.getModel());
        tableToPrint.setSize(500,1500);
        tableToPrint.getColumnModel().getColumn(0).setWidth(200);
        tableToPrint.getColumnModel().getColumn(1).setWidth(200);
        try {
            tableToPrint.print();
        } catch (PrinterException ex) {
            ex.printStackTrace();
    public static void main(final String args[]) {new PrintTableDemo().setVisible(true);}
}

Similar Messages

  • How to print a JTable  in Java Swing ?

    Hi,
    I have an application written in java swing.Now I want to write a print module that prints some details.The details includes the JTextArea and JTable that changes in size dynamically.One solution i found is to put them in a panel and print that panel.But it is static.The size of JTable and JTextArea changes, according to the given input.Please give me a solution for this.

    Printing is a bit of a nightmare, actually. Most of the trouble is layout. Basically a Printable is passed a page number and a graphics context and has to work out what components go on that page and where. It can't depend on the pages being requested in sequence.
    You can call getPrintable from a JTable, and you can call that through your own Printable in order to add extra pages. However you can't ask a Printable how many pages it's going to produce, you just have to invoke it and see if it returns a code to say that the page is out of range.
    And the Printable JTable generates is very limited, the table has to occupy full pages, you can't tell it to start in a different place on the first page, or find out how much space it's used on the last page. The headers and footers generate JTable's own idea of a page number, not yours.
    You can call print() on most Swing components, but you'll need to set their size and location first, and/or mess with the transformation in the graphics context.

  • How to print entire print component

    I have an application with fixed height & width. I have a
    list component that displays additional content when an item is
    clicked. I want to be able to print the entire list with each
    item's additional text. I'm only getting a part of the data.
    I created a print component to format the material correctly
    (component's name is plPrintRenderer in the attached code). That
    component in turn has a list component with a list itemRenderer
    (named plItemRenderer in the attached code).
    The sequence I'm using is summarized as follows:
    Create the print job.
    Start print job.
    Create an instance of the print renderer.
    Put the print renderer instance on the stage (in this case,
    in the parent application).
    Make the instance invisible.
    Give the print renderer instance a data source -- the same as
    the displayed list data source.
    Add the print renderer instance to the print job.
    Send the print job to the printer.
    The printed output contains only the amount of the print
    renderer that can be seen on the page, not the entire data. How can
    I print the entire content if it can't be displayed on a page
    (because of the fixed pixel size)?
    Any ideas?
    Thanks! I really need to get this working.

    I cannot get a good grasp on your containers for all this
    from the code you supply.
    However, when I've done similar work it is usually because
    the container that contains the items to print is being clipped by
    it's parent container.
    Try setting the parent container's clipContent property to
    false.
    Sorry to be a bit vague.
    Ian

  • How to print the Jtable into paper

    im facing a problem which is after i get the data to be dispaly in the jtable but im facing problem of printing the table in paper as a report.. the report must be info about the data in table..thanks

    My table has narrow columns resulting in clipping of
    text. Is there some way to print the full text in the
    columns?I researched Manning's Swing book and found an example of printing the content of JTable without clipping. But alas, my table doesn't fit in a standard 8.5''x11'' paper even in landscape setting. When one looks at Excel's spreadsheet output, the columns can span over multiple pages. I can live with that. Any solutions?

  • How to print entire BTC Log?

    I have a Batch Input Session with hundreds of errors of all types.    Is there a way to print the entire log rather than going down transaction by transaction to see what the errors are?

    Hello,
    in  the screen 'Batch-Input log for session ......' you could  simply use the print button in the upper row -
    you'll get the list in an ALV-screen.
    At least in ECC 5.0.
    Regards Wolfgang

  • 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.

  • How can I print a JTable with varying sized rows?

    How can I print a JTable with varying sized rows?
    I am using java 1.5, and have made a cell renderer to display multiple lines in rows and it works well, however when I use the new print method it doesn't separate the cells onto the next page, it cuts them and will print the rest of the row on the next page. Does anyone know how I might go about making this happen?
    cheers

    I finally found out the reason, The column heights were being set through my renderer. If I hadn't viewed them in the scrollpane the row heights were set to the default height of 16 therefore when the print method was called it clipped all the rows wrong, what is weird though is that the row height printed out correctly but the clipping area was set wrong because it was getting the default value of 16 from rowHeight(row).

  • Been using Macs since classic. Using MBP, OS 10.7.5. Trying to figure out how to print/save folder contents (Name, Date Modified, Size Kind) of entire (non-visible) folder? Any apps that can do this?

    Been using Macs since before classic. Using MBP, OS 10.7.5. Trying to figure out how to print/save folder contents including what's not visible on screen (Name, Date Modified, Size Kind) in entire folder?
    Screen shots are getting old hat.
    Tried select all, copy, paste into pages, but it didn't display date modified, size & kind, and also included images of selected files, which is too large. 
    Any apps/shortcuts/utilities that can do this?  Thanks in advance.

    Hello Achates:
    I did not read the rather long post. If you wish to reinstall OS X 10.4, use your software install DVD. Backup is essential. To minimize your risk, I would use an archive and install:
    http://docs.info.apple.com/article.html?artnum=107120
    In that way, you will have a fresh copy of OS X and your current settings will be preserved.
    Incidentally, I do not agree that the printer problem is best solved by reinstalling OS X. I have had HP printers for sometime and, on one occasion, had difficulty after an upgrade. HP technical support walked me through uninstalling all traces of the HP driver and then reinstalling.
    Barry

  • How to print jTable with custom header and footer....

    Hello all,
    I'm trying to print a jTable with custom header and footer.But
    jTable1.print(PrintMode,headerFormat,footerFormat,showPrintDialog,attr,interactive)
    does not allow multi line header and footer. I read in a chat that we can make custom header and footer and wrap the printable with that of the jTable. How can we do that..
    Here's the instruction on the chat...
    Shannon Hickey: While the default Header and Footer support in the JTable printing won't do exactly what you're looking for, there is a straight-forward approach. You can turn off the default header/footer and then wrap JTable's printable inside another Printable. This wrapper printable would then render your custom data, and then adjust the size given to the wrapped printable
    But how can i wrap the jTable's Printable with the custom header and footer.
    Thanks in advance,

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

  • How to print JTable to image file?

    Hi ppl.
    I have JTable that i can print via Printable to printer very well.
    Now I have a task to pass this JTable to MS Word. I can pass to MS Word any image file. So all I need is to "print" my JTable to image. Is it possible to reroute printing process to image file?
    Or any other ideas how to sovle a problem?

    John Bo wrote:
    Hi ppl.That words is 'people'. By leaving out three letters, you do not appear cool, just lazy & foolish.
    I have JTable that i can print via Printable to printer very well.
    Now I have a task to pass this JTable to MS Word. I can pass to MS Word any image file. So all I need is to "print" my JTable to image. Is it possible to reroute printing process to image file?Create a <tt>BufferedImage</tt> the same size as the <tt>JTable</tt>. Call <tt>createGraphics()</tt> on the <tt>BufferedImage</tt>. Pass the <tt>Graphics</tt> object to <tt>JTable.painComponent(Graphics)</tt>. Create an image of the <tt>BufferedImage</tt> by calling <tt>ImageIO.write()</tt>.

  • How to Print The Entire Course as PDF file from "The Sun Learning CD-ROM"

    Is anyone able to print entire course as PDF file? I'm currently learning Solaris 10 OS and trying to print the full course/module on CDS-200-S10: Intermediate System Administration for Solaris 10 Operating System CD but unsuccessful.
    It seems like I can only print individual page from each module. I have Adobe Acrobat installed on my system. Your helps is greatly appreciated.

    Hi Ankur Ver,
    This forum is to discuss problems of Windows Forms. Your question is related to itextsharp, it is the third-party library.
    You can consider contacting the official for supports, Thanks for your understanding.
    Best regards,
    Youjun Tang
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How to default Preview/Finder to print "Scale to Fit Print Entire image/Fill Entire Paper"?

    Hello all,
    I have to print PDFs. Preview or printing directly from Finder prints scaling 100% and many many times the edges of the PDFs are left outside of the printing area. I have the correct paper size selected (A4) and actually the PDFs are also A4 but for some reason 100% zooms in a bit and cuts the sides of the print outside.
    I can of course fix this by selecting Scale to Fit and Print Entire Image but I do have to do this every single time I open a PDF. I want to make this option my default! And preferrably so that I can use CMD+P from Finder to print directly without having to open the PDF. I already know what is in it...
    I have tried different Terminal tricks I have found searching the web but no luck, this and others with Preview closed before executing the command
    defaults delete com.apple.Preview PVImagePrintingScaleMode
    Please help and make my life easier. Cannot be this hard.

    I got a work around for this. Instead of using RTF template, I used Microsoft Excel itself as template and did the formatting in excel.
    thanks,
    Vijay

  • How to print selected cells in numbers

    Does anyone know how to print selected cells in a Numbers spreadsheet, rather than printing the entire sheet?
    Also, how to save the selected cells as a pdf file without saving the irrelevant cells?

    Hi nmygs,
    How about this?
    Cell A1 is a Pop-Up Menu containing names of the various "Departments"
    Other cells contain formulas to find a match for whatever is chosen in A1 from the Very Big Data Table.
    Reusable Print Me table.
    Regards,
    Ian.

  • Print a JTable with several Header and Footers

    Hi everybody,
    my name is Lothar and I come from Germany. My english is not very well, but I hope you understand me an my problem.
    I want to print a JTable, but I want to print a header with several headers and footers.
    For example:
    h3. Header
    h5. 1. Subtitle
    h5. 2. Subtitle
    Table
    h5. 3. Subtitle
    h5. Footer
    But, I do not know how I can do that. Can anybody tell me, how I can solve my problem. Please, explain for a newbie because I have learned Java since two months ;)
    Here the code:
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.Date;
    import javax.swing.*;
    public class Beispiel extends JFrame implements ActionListener {
        private JTable table;
        public static void main(String[] args) {
            Beispiel tl = new Beispiel();
            tl.setVisible(true);
            tl.pack();
        public Beispiel() {
            setLayout(new BorderLayout());
            // DruckButton
            JButton print = new JButton("Print");
            add(print, BorderLayout.SOUTH);
            print.addActionListener(this);
            // Tabelle
            add(new JScrollPane(createTable()), BorderLayout.CENTER);
            // schlie&szlig;t das Frame
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public JTable createTable() {
            // titel
            String[] title = new String[] { "Datum", "Von", "Bis",
                    "Dauerinsgesamt", "Bemerkung" };
            // daten
            String[][] data = new String[][] { { "", "", "", "", "" },
            table = new JTable(data, title);
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
            return table;
        public void actionPerformed(ActionEvent e1) {
            MessageFormat header = new MessageFormat("Header");
            MessageFormat footer = new MessageFormat("Footer");
            try {
                table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
            } catch (Exception e2) {
                System.err.format("Cannot print %s%n", e2.getMessage());
    }

    Nobody?
    Can nobody solve my problem?

  • Problem printing the JTable

    Hi all,
    I have a problem with printing JTable.
    My application has a submit button,JTable and Print Button.
    As I click on the Submit button, the data is retrieved from the Database(MS Access) and displayed on the JTable.
    Now when I click on the Print button, the printer properties dialog box is displayed. But when I click on the print button in the dialog box, nothing is printed on the paper.
    I checked the printers and faxes in the control panel, It showed Java printing under the Document name and Printing under the Status. It is displayed for sometime and then disappeared after some time. But nothing is printed on the paper(not even the blank paper).
    I tried a lot but couldn't understand the problem.
    I have used the following files:
    PrintJTable.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import java.applet.*;
    import java.sql.*;
    import java.util.*;
    import java.net.*;
    import java.lang.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    class PrintJTable implements ActionListener,Printable
    Connection connect;
    ResultSet rs;
    JTable table;
    JScrollPane tableAggregate;
    DisplayTable displayTable;
    JButton print,submitButton;
    public PrintJTable()
    JFrame frame = new JFrame("Table");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}});
    connect();
    displayTable= new DisplayTable();
    JButton submitButton= new JButton("SUBMIT");
    submitButton.addActionListener(this);
    JButton printButton= new JButton("PRINT!");
    // for faster printing turn double buffering off
    RepaintManager.currentManager( frame).setDoubleBufferingEnabled(false);
    printButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    PrinterJob pj=PrinterJob.getPrinterJob();
    pj.setPrintable(PrintJTable.this);
    pj.printDialog();
    try{
    pj.print();
    }catch (Exception PrintException) {}
    tableAggregate = createTable();
    tableAggregate.setBorder(new BevelBorder(BevelBorder.LOWERED));
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(submitButton,BorderLayout.NORTH);
    frame.getContentPane().add(tableAggregate,BorderLayout.CENTER);
    frame.getContentPane().add(printButton,BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
    } // end of constructor
    public void connect()
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Opening db connection");
    connect = DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=C:/db1.mdb","","");
    catch (ClassNotFoundException ex) {
    System.err.println("Cannot find the database driver classes.");
    System.err.println(ex);
    catch (SQLException ex) {
    System.err.println("Cannot connect to this database.");
    System.err.println(ex);
    public JScrollPane createTable() {
    displayTable= new DisplayTable();
    JTable table = new JTable(displayTable);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.getTableHeader().setReorderingAllowed(false);
    JScrollPane scrollpane = new JScrollPane(table,
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    return scrollpane;
    } // end of createTable()
    public void actionPerformed(ActionEvent ie)
    try
    Statement statement6=connect.createStatement();
    ResultSet rs6=statement6.executeQuery("select * from benf_details");
    displayTable.executeQuery(rs6);
    statement6.close();
    catch(SQLException sqle)
    JOptionPane.showMessageDialog(null,"error2"+sqle);
    }// end of actionPerformed
    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();
    double pageHeight = pageFormat.getImageableHeight()-fontHeight; //leave room for page number
    double pageWidth = pageFormat.getImageableWidth();
    System.out.println("page width = " + pageWidth );
    double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
    System.out.println("table width = " + tableWidth );
    double scale = 1;
    if (tableWidth >= pageWidth) {
    scale = pageWidth / tableWidth;
    System.out.println("scale = " + scale );
    double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
    double tableWidthOnPage = tableWidth * scale;
    double oneRowHeight = (table.getRowHeight() + table.getRowMargin()) * scale;
    int numRowsOnAPage = (int)((pageHeight - headerHeightOnPage) / oneRowHeight);
    double pageHeightForTable = oneRowHeight * numRowsOnAPage;
    int totalNumPages = (int)Math.ceil(((double)table.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 );
    //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 = 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);
    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);
    table.getTableHeader().paint(g2);//paint header at top
    return Printable.PAGE_EXISTS;
    } // end of print()
    public static void main(String[] args) {
    new PrintJTable();
    }// end of PrintJTable
    DisplayTable.java
    import java.util.Vector;
    import java.sql.*;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.event.TableModelEvent;
    public class DisplayTable extends AbstractTableModel {
    Connection connection;
    Statement statement;
    ResultSet resultSet;
    String[] columnNames = {};
    Vector          rows = new Vector();
    ResultSetMetaData metaData;
    String db_uname,db_passwd;
    public DisplayTable() {
    public void executeQuery(ResultSet resultSet) {
    try {
    metaData = resultSet.getMetaData();
    int numberOfColumns = metaData.getColumnCount();
    columnNames = new String[numberOfColumns];
    // Get the column names and cache them.
    // Then we can close the connection.
    for(int column = 0; column < numberOfColumns; column++) {
    columnNames[column] = metaData.getColumnLabel(column+1);
    // Get all rows.
    rows = new Vector();
    while (resultSet.next()) {
    Vector newRow = new Vector();
    for (int i = 1; i <= getColumnCount(); i++) {
         newRow.addElement(resultSet.getObject(i));
    rows.addElement(newRow);
    // close(); Need to copy the metaData, bug in jdbc:odbc driver.
    fireTableChanged(null); // Tell the listeners a new table has arrived.
    catch (SQLException ex) {
    System.err.println(ex);
    public void close() throws SQLException {
    System.out.println("Closing db connection");
    resultSet.close();
    statement.close();
    connection.close();
    protected void finalize() throws Throwable {
    close();
    super.finalize();
    // Implementation of the TableModel Interface
    // MetaData
    public String getColumnName(int column) {
    if (columnNames[column] != null) {
    return columnNames[column];
    } else {
    return "";
    public Class getColumnClass(int column) {
    int type;
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return super.getColumnClass(column);
    switch(type) {
    case Types.CHAR:
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    return String.class;
    case Types.BIT:
    return Boolean.class;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    return Integer.class;
    case Types.BIGINT:
    return Long.class;
    case Types.FLOAT:
    case Types.DOUBLE:
    return Double.class;
    case Types.DATE:
    return java.sql.Date.class;
    default:
    return Object.class;
    // to make the cells editable
    public boolean isCellEditable(int row, int column) {
    try {
    return metaData.isWritable(column+1);
    catch (SQLException e) {
    return false;
    public int getColumnCount() {
    return columnNames.length;
    // Data methods
    public int getRowCount() {
    return rows.size();
    public Object getValueAt(int aRow, int aColumn) {
    Vector row = (Vector)rows.elementAt(aRow);
    return row.elementAt(aColumn);
    public String dbRepresentation(int column, Object value) {
    int type;
    if (value == null) {
    return "null";
    try {
    type = metaData.getColumnType(column+1);
    catch (SQLException e) {
    return value.toString();
    switch(type) {
    case Types.INTEGER:
    case Types.DOUBLE:
    case Types.FLOAT:
    return value.toString();
    case Types.BIT:
    return ((Boolean)value).booleanValue() ? "1" : "0";
    case Types.DATE:
    return value.toString(); // This will need some conversion.
    default:
    return "\""+value.toString()+"\"";
    public void setValueAt(Object value, int row, int column) {
    try {
    String tableName = metaData.getTableName(column+1);
    // Some of the drivers seem buggy, tableName should not be null.
    if (tableName == null) {
    System.out.println("Table name returned null.");
    String columnName = getColumnName(column);
    String query =
    "update "+tableName+
    " set "+columnName+" = "+dbRepresentation(column, value)+
    " where ";
    // We don't have a model of the schema so we don't know the
    // primary keys or which columns to lock on. To demonstrate
    // that editing is possible, we'll just lock on everything.
    for(int col = 0; col<getColumnCount(); col++) {
    String colName = getColumnName(col);
    if (colName.equals("")) {
    continue;
    if (col != 0) {
    query = query + " and ";
    query = query + colName +" = "+
    dbRepresentation(col, getValueAt(row, col));
    System.out.println(query);
    System.out.println("Not sending update to database");
    // statement.executeQuery(query);
    catch (SQLException e) {
    // e.printStackTrace();
    System.err.println("Update failed");
    Vector dataRow = (Vector)rows.elementAt(row);
    dataRow.setElementAt(value, column);
    }

    Java 1.5 incorporates a very simple way to print from a JTable. I am using a mysql DB but it is the same concept. Review my code and let me know if you have any questions.
    package emsmain;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.sql.*;
    import java.text.MessageFormat;
    import java.util.*;
    import javax.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.swing.*;
    import javax.swing.JTable;
    import javax.swing.table.*;
    import java.awt.print.*;
    public class TableFromDatabase extends JFrame implements ActionListener{
        JButton jbtprint = new JButton("Print Report");
        JTable Reporttable;
        Connection conn = Connect_Database.getConnection();
         public TableFromDatabase()
    Vector columnNames = new Vector();
    Vector data = new Vector();     
              try{  
                String query = null;
                Statement ps = null;
                ResultSet rs = null;
                  //Class Master List
                  if (Report_Menu.jrbMaster_list.isSelected()){
                      query =("Select * from students") ;
                  //Classes taken by student
                  if (Report_Menu.jrbClass_taken.isSelected()){
                      String taken = Report_Menu.jtfStudent.getText();
                      query = ("select program.course_num, course_name, course_start_date, course_stat_desc from registration, program where student_id = '"+taken+"' and program.course_num = registration.course_num");
                  //Birthday report
                  if (Report_Menu.jrbBirthday.isSelected()){
                      String birthday = (String) Report_Menu.jcb_birthday.getSelectedItem();
                      query = ("SELECT student_id, fname, lname, address, city, state_name, zipcode, dob FROM students where substring(dob, 6,2) = '"+birthday+"'"); 
                  //Course Catologue
                  if (Report_Menu.jrbCourseCatologue.isSelected()){
                      String course = (String) Report_Menu.jcbChooseCourse.getSelectedItem();
                      query = ("select  course_name, course_length, course_cost, course_credits from course where course_name = '"+course+"'");
                  //Certification expiration report
                  if (Report_Menu.jrbExpiration.isSelected()){
                      String month = (String) Report_Menu.jcbMonth.getSelectedItem();
                      String year = (String) Report_Menu.jcbYear.getSelectedItem();
                      query = ("SELECT FNAME, LNAME FROM STUDENTS, REGISTRATION WHERE substring(expiration_date, 6,2) = '"+month+"' and substring(expiration_date, 1,4) = '"+year+"' and registration.student_id = students.student_id") ;
                  //Class Roster
                  if (Report_Menu.jrbRoster.isSelected()){
                      String c_number = Report_Menu.jtfClassNumber.getText();
                      query = ("Select course_name, course_start_date, fname, lname from program, registration, students where program.course_num = '"+c_number+"' and registration.student_id = students.student_id;");
                  //Squad list and counts
                  if (Report_Menu.jrbSquadCount.isSelected()){
                      query = ("SELECT Squad_Name, count(student_id) from students group by Squad_Name");
                  //Student List
                  if (Report_Menu.jrbStudent_list.isSelected()){
                      String Choose_month = (String) Report_Menu.jcbcourse_month.getSelectedItem();
                      String Choose_Course = (String) Report_Menu.jcbcourse_name.getSelectedItem();
                      query = ("select count(student_id) from (registration, program) where program .course_name = '"+Choose_Course+"' and substring(course_start_date, 6,2) = '"+Choose_month+"'and registration.course_num = program.course_num;");
                ps = conn.createStatement();
                //Run Selected Report
                ps.execute(query);
                rs = ps.executeQuery(query);
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                //  Get column names
                for (int i = 1; i <= columns; i++)
                    columnNames.addElement( md.getColumnName(i) );
                //  Get row data
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++)
                        row.addElement( rs.getObject(i) );
                    //add row data to JTable
                    data.addElement( row );
                rs.close();
                ps.close();
            catch(Exception e)
                JOptionPane.showMessageDialog(null,e.getMessage());
            //  Create Jtable with database data 
            Container c = getContentPane();
            c.setLayout(new BorderLayout());
            Reporttable = new JTable(data, columnNames);
            JScrollPane scrollPane = new JScrollPane( Reporttable );
            c.add( scrollPane );
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
            buttonPanel.add(jbtprint);
            c.add(buttonPanel,BorderLayout.SOUTH);
            jbtprint.addActionListener(this);
        public void actionPerformed(ActionEvent e){
             if(e.getActionCommand().equals("Print Report")){
               PrintForm();
    public void PrintForm(){ 
         try {
             String name = null;
             // Will display correct heading for print job
             if (Report_Menu.jrbMaster_list.isSelected()){
             name = "Master List";
             if (Report_Menu.jrbBirthday.isSelected()){
             name = "Birthday List";
             if (Report_Menu.jrbClass_taken.isSelected()){
             name = "Classes taken by Student";
             if (Report_Menu.jrbCourseCatologue.isSelected()){
             name = "Course Catalogue";
             if (Report_Menu.jrbExpiration.isSelected()){
             name = "Certification Expiration Report";
             if (Report_Menu.jrbRoster.isSelected()){
             name = "Class Roster";
             if (Report_Menu.jrbSquadCount.isSelected()){
             name = "Squad list with Student Counts";
             if (Report_Menu.jrbStudent_list.isSelected()){
             name = "Student count by Course";
             // fetch the printable
             Printable printable = Reporttable.getPrintable(JTable.PrintMode.FIT_WIDTH,
                                                      new MessageFormat(name),
                                                      new MessageFormat("Page - {0}"));
             // fetch a PrinterJob
             PrinterJob job = PrinterJob.getPrinterJob();
             // set the Printable on the PrinterJob
             job.setPrintable(printable);
             // create an attribute set to store attributes from the print dialog
             PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
             // display a print dialog and record whether or not the user cancels it
             boolean printAccepted = job.printDialog(attr);
             // if the user didn't cancel the dialog
             if (printAccepted) {
                    try {
                          // do the printing (may need to handle PrinterException)
                        job.print(attr);
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
         } finally {
             // restore the original table state here (for example, restore selection)
    }

Maybe you are looking for

  • 2400MP display in black and white

    Can someone help me out,  Just last week my project only displays in black and white. I have gone through evey setting I can find but don't know what the issue is.

  • I do not remember the answers to my security questions

    I need help reseting the answers to my security questions.

  • Smart object in PSD CS5`

    Why does ps create a temp ai file when placing smart object? Editing is linked temporary file instead of original.

  • HTC S620 problems

    I've had one of these phones since the basic 'free' offer in 2008(?). I only use the phone for texts/phone (not internet) and only have the basic 50 texts/minutes package (which I never fully use!!) Recently it has started playing up - not charging p

  • Audit search

    Hi! I have 2 questions regarding audit in OCS: 1- If audits are enabled ( via EM), do you see something in the ocs web console? 2- Im getting an fdk AccessDenied exception when calling auditM.searchAuditHistory() using the orcladmin account. If this