Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Problem printing the JTable

843805Feb 24 2007 — edited Feb 25 2007
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);

}
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 25 2007
Added on Feb 24 2007
1 comment
126 views