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)
}

Similar Messages

  • Problem in printing the JTable values

    Dear Friends,
    I have to print the JTable values (on paper using print dialogue box).
    I'm using jtableObj.print to print the table values. But jtableObj.print takes more time to print the table values because it prints the values as a image(approximately 5 mins to print 10 pages).
    My code is ,
    boolean complete = tableObj.print(mode, header, footer, showPrintDialog, null, interactive,
                                  null);Could anyone please tell me how to reduce the time?
    Thanks in advance

    Hi again,
    1. what problem are u facing ?
      (there is no sapscript symbol / system symbol
       for finding out the length )
      (In abap u can use strlen)
    2.  data and gets trimmed
       what is the meaning of it ?
    3. do u mean to say that  !
      ABCDEF                     123 45
      GEF                        123 45
      is getting pritned like
      ABCDEF 123 45  ?
      GEF  123 45
    4. If so , then use TABS
    5. This happens because SPACE
       is different in different varlues of
       ABCDEF and GEF !
    regards,
    amit m.
    Message was edited by: Amit Mittal

  • I am using Firefox ver. 3.0.19 and I have Windows 7. When I use Firefox as a browser I cannot print my emails. I get an error message: "pcfax not availabe". If I use IE I have no problem printing the emails.

    I am using Firefox ver. 3.0.19 and I have Windows 7 which came with a new computer. When I use Firefox as a browser I cannot print my emails. I get an error message: "pcfax not availabe". If I use IE I have no problem printing the emails.
    == This happened ==
    Every time Firefox opened
    == From day 1 with the new computer about two weeks ago.

    It sounds like you have the wrong printer selected.
    When you get the Print window, pick another printer from your printer dropdown. You seem to have a fax printer selected instead of a physical printer.

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

  • Problem printing the methods due to lack of understanding

    Okay, i'm pretty sure i have all my code correct except for the System.out.println's at the top to print the methods below. What am i doing wrong? Its suppose to be a program that prompts for amount of random numbers, the first part sorts/finds the median, and the second part finds the mode.
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class Assignment2part1
    public static void main (String arg[])
         String numRandomNum= JOptionPane.showInputDialog("How many random numbers would you like?");
       int setRandomNum = Integer.parseInt(numRandomNum);
         Random num = new Random();
         for (int i = 0; i < setRandomNum ; i++)
                int number =num.nextInt(10) + 1;
                System.out.println(number);
              System.out.println(median(number[] ));   // #############################Problem here
              System.out.println(mode(????));     // #################################Problem here
    public static void median (int[] a)
              int temp=0;
              for (int i=0; i<a.length; i++)
                   for (int j=0; j<a.length; j++)
                   if (a[i] > a[j])
                        temp = a;
                        a[i] = a[j];
                        a[j] = temp;
              if (a.length%2==1)
                   return a[a.length/2];
                   else
                        return ( a[a.length/2] + (a[a.length/2]-1)/2 );
    public static int mode (int[] a)
         int mostFreqNum=-1, mostFreqCount=1, noModeFlag=0, cNum=0, cCount=0;
         for (int i=0; i<a.length; i++)
              cCount=1;
              cNum=a[i];
              for (int j=0; j<a.length; J++)
                   if (i!=j && a[j] != mostFreqNum && a[j] == cNum)
                        cCount++;
              if (cCount>mostFreqCount)
                   mostFreqCount=cCount;
                   mostFreqNum=cNum;
                   noModeFlag=0;
              else if (cCount==mostFreqCount)
                   noModeFlag=1;
              if (noModeFlag=1)
                   return -1;
              else
                   return mostFreqNum;

    No, i completely understand, so it needs to be in the main section, SO would it be something like.......
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    public class Assignment2part1
    public static void main (String arg[])
         String numRandomNum= JOptionPane.showInputDialog("How many random numbers would you like?");
       int setRandomNum = Integer.parseInt(numRandomNum);
         Random num = new Random();
         for (int i = 0; i < setRandomNum ; i++)
                int number =num.nextInt(10) + 1;
                System.out.println(number);
              int [] a= {number};          //#################Edited
              System.out.println(median(number[] ));
              System.out.println(mode(
    public static int median (int[] a)
              int temp=0;
              for (int i=0; i<a.length; i++)
                   for (int j=0; j<a.length; j++)
                   if (a[i] > a[j])
                        temp = a;
                        a[i] = a[j];
                        a[j] = temp;
              if (a.length%2==1)
                   return a[a.length/2];
                   else
                        return ( a[a.length/2] + (a[a.length/2]-1)/2 );
    public static int mode (int[] a)
         int mostFreqNum=-1, mostFreqCount=1, noModeFlag=0, cNum=0, cCount=0;
         for (int i=0; i<a.length; i++)
              cCount=1;
              cNum=a[i];
              for (int j=0; j<a.length; J++)
                   if (i!=j && a[j] != mostFreqNum && a[j] == cNum)
                        cCount++;
              if (cCount>mostFreqCount)
                   mostFreqCount=cCount;
                   mostFreqNum=cNum;
                   noModeFlag=0;
              else if (cCount==mostFreqCount)
                   noModeFlag=1;
              if (noModeFlag=1)
                   return -1;
              else
                   return mostFreqNum;
    I'm still not quite sure on the syntax of the print ln, what needs to go into the ().   I appreciate the step by step help                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problem printing the Detail-Trail Balance Standard report

    Iam trying to print the detail trial balance report in GL. Iam getting the report output correctly. But when iam printing the report, the last line of every page is spilling out on to the next page and then there is a page break(which is expected). and then this scenario continues till the end of the report. i,e the last line of every page is spilling out on next page,,then page break,, then goes on...till end of report.
    It will be so nice of you if anyone can help me in figuring it out why its behaving like this after printing.?? waiting for your reply??
    thankyou

    Check printer's top and bottom margin, when you send it for printing. Or open report in report builder and reduce margin of the header/main/trailer sections.

  • Problem printing the output

    i'm writing a getClassMean() which is going to compute the Mean score of the whole class. in the following myLines is a ArrayList object that stores each String from my input file, which look something like:
    Stevens, Frank, Z.; 87, 86, 92, 78, 86
    Franklin, Susan, A.; 98, 88, 94, 98, 95
    Bowers, Brett, B.; 85, 78, 83, 84, 89
    This is the method in the Mean class:
    protected ArrayList<Double> classGrades = new ArrayList<Double>();
    public double getClassMean(){
                String gb;
                String[] array, grades;
                double mean;
                double score;
                for(String l : myLines) {
                    array = l.split("; ");
                    gb = array[1];    //gb --grade block
                    grades = gb.split(", ");
                    for(String scoreStr : grades ) {
                        score = Double.parseDouble(scoreStr);
                        classGrades.add(score);
                double sum = 0.0;
                for(double d : classGrades) {sum += d;}
                mean = sum / classGrades.size();
                return mean;
            }and the Driver program has this:
    Mean m = new Mean();
    double classMean = mean.getClassMean();
    System.out.println(classMean);but the output print something i don't understand:
    NaN
    can someone tell me what's going on? thanks!

    NaN is "Not a Number" it comes from doing operations with undefined results, like 0.0 / 0.0 .
    Print out sum and classGrades.size() before doing that division, then trace backwards (add more print statements if you need to) to find your bug.

  • 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);}
    }

  • Since downloading the most current iTunes software I can no longer print the insert (label) for a jewel case.  The songs are printed over each other and can not be read.  Any suggestions?  Thanks.

    Since downloading the most current iTunes software I am no longer able to print an insert (label) for a jewel case.  I click on print, choose jewel case and then it doesn't matter which option I choose for the insert it will only print the songs over each other in a 1 inch section so that it can not be used or read.  If instead of clicking on the jewel case I click on list it works fine and prints an appropriate list.  I have always updated the iTunes software the first time I am offered to do so and I have never had a problem printing the jewel case inserts.  Since this issue is not about a piece of hardware iTunes help will not help me. 

    Did you ever get a response?
    If you so how did you correct the problem?
    I have the exact problem you had.
    Please let me know.
    Thank you
    <Edited by Host>

  • Urgent: how to print the contents displayed in JTextPane

    hi all,
    i've a problem printing the contents typed in styled format in JTextPane, when i print the contents nothing is printed. can anyone tell how can i print the contents typed in styled format or so. the code for implementing the print is given below.
    class ContentsArea extends JTextPane implements Pritable {
       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());
          g2d.translate(pf.getImageableWidth() / 2,
                          pf.getImageableHeight() / 2);
          Dimension d = getSize();
          double scale = Math.min(pf.getImageableWidth() / d.width,
                                    pf.getImageableHeight() / d.height);
          if (scale < 1.0) {
              g2d.scale(scale, scale);
          g2d.translate(-d.width / 2.0, -d.height / 2.0);
          return Printable.PAGE_EXISTS;
    }i'd be grateful to all ppl who helps me.
    Afroze.

    What's the exact problem? The printer printing a blank sheet or the printer not doing anything at all? First make sure in the main program you've got something along the lines of...
    import java.awt.print.*;
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    PageFormat pageFormat = printerJob.defaultPage();
    if(!printerJob.printDialog()) return; //not essential but lets the user tweak printer setup
    pageFormat = printerJob.pageDialog(pageFormat); //ditto
    printerJob.setPrintable(this, pageFormat);
    print(...);
    The above code should go in an ActionListener, triggered when the user hits a print button or menuitem. I'm guessing you already have something similar set up.
    Then your print(...) method should be similar to
    public int print(Graphics g, PageFormat pageFormat, int pageIndex)
         if(pageIndex>0) return NO_SUCH_PAGE;
         Graphics2D gg = (Graphics2D)g;
         gg.draw(whatever's going to be printed);
         return PAGE_EXISTS;
    Which it is, although yours has clever scaling stuff built in ) The only thing you're not doing is rendering the actual content.
    So if you want the contents of the textpane, it'd make sense to use something like g.drawString(myTextPane.getContents()); in the print method. Note it's g and not g2d, since Graphics2D has more complicated text handling routines.
    I'm no expert tho )

  • Problems printing a digitally signed PDF

    Hi
    I'm having problems printing a digitally signed PDF on a dell 968 AIO printer. It works fine on the a majority of printers but we have had reports of issues with other models as well as the dell printer.
    The PDF prints fine when opened in Adobe Reader 9 (blue bar appears at top to indicate signed pdf).
    When opened in Adobe Acrobat 7 on the same PC the first pages prints correctly but the rest of the pages print only a few lines in a huge font and the characters are backwards.
    The pdf does not always open in reader when accessed through the web it will sometimes open with acrobat is there anyway to control this?
    Does anyone know why this maybe happening?
    Thanks
    Claire

    Thanks for the reply Mike. I think I've got a little further with this problem now. There seems to be a problem printing the signed PDF in adobe reader 7 as well as acrobat 7.
    I have uninstalled acrobat from the machine but the problem still happens with reader 7.
    Does anyone know if reader 7 and below has any known issues printing signed pdf's. It works fine on 8 and above.
    thanks
    Claire

  • Problem printing Report Document Draft

    Dear support,
    our customer has problem printing its Document Draft Report, because
    the "DRAFT DOCUMENT" string on the background of the page is too large.
    The printer can manage this dimension and prints an empty second page
    (also when the document has more pages).
    See attached file.
    If we disable the "Print Draft Watermark on Draft Document" flag in the
    Print Preferences, the customer hasn't the problem printing the draft
    document.
    The customer need to distinguish the print of draft document.
    Is it possible in the report designer to know if a document is a Draft or
    a Definitive one?
    If we can understand the type of the document, we could add a text box
    "DRAFT DOCUMENT" in the report and disable the "Print Draft Watermark on
    Draft Document" flag.
    Can someone help us, please?
    Regards,
                  Emanuele
    TC Systems SA - Mendrisio - CH
    Emanuele Croci
    +41 (0)91 960 2525

    hi Emanuele Croci,
    For example paper format which default as Letter,but in PLD
    if y'r paper format is A4 then definitely it will be printed more than 1 page.
    Go to File --> Page Set Up --> Change paper format as in PLD.
    Also reduce the font by 1 point.
    If problem not get solved,You can print Water mark as DRAFT from printer properties.
    Start --> Printer and Faxes > Select Printer you want to print,Right Click it>Select Properties>Select Printing Preferences>Select Effects Tab> Select Water mark option as Draft>Click Apply.
    Test print it let me know.
    Hope above solution will solve problem.
    Jeyakanthan

  • Problem Printing Front Panel

    I'm having a problem printing the front panel of a particular VI.  When I set the print option to Standard Printing the printer prints nothing.  When set to Bitmap Printing it works, but it's not the type of printout that I want.  In both cases the Print Preview appears the same.  Also, all my other VI's print in Standard Printing mode with no problems.
    I've read other posts indicating that the cause may be that the VI is sending a print code to the printer telling it not to print.  How can I determine if this is the case?  If it is the case, how do I fix it?  This VI's front panel has nothing special about it relative to other VI's that print correctly.
    Any help would be greatly appreciated.

    If it happens using the menu, then it's not that your code sends a "do not print" action to the printer.
    Try copying front panel items, one or two at a time, from your wonky VI to a new VI, and print the new VI after every move.
    Maybe you can find one item that causes it.
    If you're on a Mac, print it to a PDF file, and see if that's OK. If you're on Windows, you can use Print2PDF or something similar to act like a printer and show you what the printout would be.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

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

  • My problem is that after printing the first photo or picture, when I come to print a second, both the Colour Management and Epson Colour Controls are greyed out and showing No Colour Management

    I have recently purchased a Mac computer (updated to Maverick) to go with my Epson Stylus Photo RX500 printer which has given excellent service with my old Windows computer. However, when trying to print pictures or photos via Photoshop Elements 11, the best results I can get are using the Colour Management and Epson Colour controls in the printing options box.
    My problem is that after printing the first photo or picture, when I come to print a second, both the Colour Management and Epson Colour Controls are greyed out and showing No Colour Management, The only way I can reset the controls is to shut down the printer and computer and restart.
    Could there may be a setting somewhere that I need to adjust please?  I have been in touch with Epson and they say that the Epson Colour controls are part of the Photoshop Elements software but a post on the Adobe forum brought no results and I am unable to contact Adobe.
    <Edited by Host>

    Hello Garry. Thanks for the reply. I guess I should have used a different title from "How do I post a question?" That should come after trying to resolved the colour settings first. However, to answer your question, after experimenting with all the different settings in Photoshop Elements and Epson software, I now start with PSE11 Colour settings then click "no colour management" then after clicking Print, I choose "More Options/Colour Management/Colour Handling/Printer Manages Colour" then I choose "Page Setup/Layout/Colour Matching" which then shows Epson Colour Controls but I also choose "Layout/Colour Management" which then shows "Colour Controls/Mode" I then of course choose an Epson printer profile depending on the paper I am using. I get good results but as I said, the Colour Matching and Colour Controls are then greyed out. Hope that makes sense.

Maybe you are looking for

  • Can I add internal storage to a mac mini?

    I am out of space and have plenty of external storage,   I just think that it works better with internal storage.

  • LoadJava Privilege Error

    While loading a .jar using loadjava in Oracle 8.1.5 I had this error on all the classes within the jar. Does anyone know what the problem is ? Error while creating class javax/mail/internet/NewsAddress ORA-01031: insufficient privileges Error while c

  • Can no longer sync photos via itunes

    iTunes has quit syncing photos to my devices (iPad, iPhone). First I noticed that some photos were not synced by comparing to original folder contents. I tried removing all photos by deselecting the Sync Photos option and deleting the iTunes Photo Ca

  • How to create special column which represents result of a query

    Hi all, I need your help once more. The situation is the following: I have a table MESSAGE which has some billion entries. The columns are msg_id, vehicle_id, timestamp, data, etc. I have another table VEHICLE which holds static vehicle data (about 2

  • Why is Photoshop Elements 10 trial not installing?

    I went to the older software page, installed File 1 (Photoshop Elements 10), but I can't install File 2. An error message shows up, something along the lines of "all files must be stored in the same folder", etc. I am not a computer genius. I am gett