Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: how to print a Jtable that retrieves data from the database.

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default how to print a Jtable that retrieves data from the database.

    It have error
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 18
    t sun.font.ExtendedTextSourceLabel.getJustificationI nfos(ExtendedTextSourceLabel.java:946)
    at java.awt.font.TextLine.getJustifiedLine(TextLine.j ava:1353)
    at java.awt.font.TextLayout.getJustifiedLayout(TextLa yout.java:808)
    at sun.swing.SwingUtilities2.drawString(SwingUtilitie s2.java:511)
    at sun.swing.SwingUtilities2.drawStringUnderlineCharA t(SwingUtilities2.java:593)
    at javax.swing.plaf.synth.SynthGraphicsUtils.paintTex t(SynthGraphicsUtils.java:340)
    at javax.swing.plaf.synth.SynthGraphicsUtils.paintTex t(SynthGraphicsUtils.java:319)
    at javax.swing.plaf.synth.SynthGraphicsUtils.paintTex t(SynthGraphicsUtils.java:410)
    at javax.swing.plaf.synth.SynthLabelUI.paint(SynthLab elUI.java:213)
    at javax.swing.plaf.synth.SynthLabelUI.update(SynthLa belUI.java:177)
    at javax.swing.JComponent.paintComponent(JComponent.j ava:778)
    at javax.swing.JComponent.printComponent(JComponent.j ava:1218)
    at javax.swing.JComponent.paint(JComponent.java:1058)
    at javax.swing.plaf.synth.SynthTableUI$SynthTableCell Renderer.paint(SynthTableUI.java:827)
    at javax.swing.CellRendererPane.paintComponent(CellRe ndererPane.java:151)
    at javax.swing.plaf.synth.SynthTableUI.paintCell(Synt hTableUI.java:693)
    at javax.swing.plaf.synth.SynthTableUI.paintCells(Syn thTableUI.java:581)
    at javax.swing.plaf.synth.SynthTableUI.paint(SynthTab leUI.java:365)
    at javax.swing.plaf.synth.SynthTableUI.update(SynthTa bleUI.java:276)
    at javax.swing.JComponent.paintComponent(JComponent.j ava:778)
    at javax.swing.JComponent.printComponent(JComponent.j ava:1218)
    at javax.swing.JComponent.paint(JComponent.java:1058)
    at javax.swing.JComponent.print(JComponent.java:1200)
    at javax.swing.TablePrintable.print(TablePrintable.ja va:384)
    at javax.swing.JTable$ThreadSafePrintable$1.run(JTabl e.java:6498)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:721)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 691)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:155)
    at java.awt.WaitDispatchSupport$2.run(WaitDispatchSup port.java:182)
    at java.awt.WaitDispatchSupport$4.run(WaitDispatchSup port.java:221)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.awt.WaitDispatchSupport.enter(WaitDispatchSup port.java:219)
    at java.awt.Dialog.show(Dialog.java:1077)
    at java.awt.Component.show(Component.java:1651)
    at java.awt.Component.setVisible(Component.java:1603)
    at java.awt.Window.setVisible(Window.java:1014)
    at java.awt.Dialog.setVisible(Dialog.java:1003)
    at sun.swing.PrintingStatus.showModalOnEDT(PrintingSt atus.java:203)
    at sun.swing.PrintingStatus.showModal(PrintingStatus. java:171)
    at javax.swing.JTable.print(JTable.java:6307)
    at javax.swing.JTable.print(JTable.java:6112)
    at javax.swing.JTable.print(JTable.java:6067)
    at checkstock.History.actionPerformed(History.java:23 3)
    at javax.swing.AbstractButton.fireActionPerformed(Abs tractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed (AbstractButton.java:2341)
    at javax.swing.DefaultButtonModel.fireActionPerformed (DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultB uttonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.jav a:6505)
    at javax.swing.JComponent.processMouseEvent(JComponen t.java:3321)
    at java.awt.Component.processEvent(Component.java:627 0)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Container.java:4832)
    at java.awt.LightweightDispatcher.processMouseEvent(C ontainer.java:4492)
    at java.awt.LightweightDispatcher.dispatchEvent(Conta iner.java:4422)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2273)
    at java.awt.Window.dispatchEventImpl(Window.java:2719 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:723)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:682)
    at java.awt.EventQueue$3.run(EventQueue.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:696)
    at java.awt.EventQueue$4.run(EventQueue.java:694)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 693)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:97)
    This is my code
    package checkstock;
     
    import com.mysql.jdbc.Statement;
    import java.awt.event.ActionEvent;
    import java.sql.ResultSet;
    import java.text.MessageFormat;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.swing.JTable;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
     
    /**
     *
     * @author Anawin
     */
    public class History extends javax.swing.JFrame implements java.awt.event.ActionListener{
    private java.sql.Connection con = null;
        private boolean checkTable;
        private Statement prepstmt;
        private java.sql.Statement st;
        private ResultSet rs;
        private String dataValues[][];
        private int count;
        private HashPrintRequestAttributeSet attr;  
        ConnectDB c = new ConnectDB();
        /**
         * Creates new form History
         */     
        public History() {
            con = c.getConnectDB();
            initComponents();       
    setTitle("History Page");
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setSize(980,730);
    setLocationRelativeTo(null);
    if(checkTable == false)
    {
    dataValues = new String[10][10];
    checkTable = true;
    }
    DefaultTableModel df = new DefaultTableModel();
    String[] columnNames = {"ชื่อผู้คืนล่าสุด", "อุปกรณ์ที่คืนล่าสุด", "วันที่คืนล่าสุด", "สภาพอุปกรณ์ล่าสุด"};
    try{       
               String sqlStr = "select * from eqreturn";
               prepstmt = (Statement) con.createStatement();
               rs =  prepstmt.executeQuery(sqlStr);        
               while(rs.next())
               {
                    dataValues[count][0] = ""+rs.getString("name");
                    dataValues[count][1] = ""+rs.getString("eq");
                    dataValues[count][2] = ""+rs.getString("date_return");
                    dataValues[count][3] = ""+rs.getString("status");
                    df.setDataVector(dataValues,columnNames);
                    jTable1.setModel(df);
                    count += 1;            
               }
               rs.close();
               prepstmt.close();
     }catch(Exception e)
     {
      System.out.println("Database Error");
      System.out.println("Error message:"+e);
     }
        }
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTable1 = new javax.swing.JTable();
            jButton2 = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "ประวัติการยืมคืน", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("TH SarabunPSK", 0, 36))); // NOI18N
     
            jButton1.setFont(new java.awt.Font("TH SarabunPSK", 0, 24)); // NOI18N
            jButton1.setText("BACK HOME");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            jTable1.setFont(new java.awt.Font("TH SarabunPSK", 0, 18)); // NOI18N
            jTable1.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                },
                new String [] {
                    "ชื่อผู้คืนล่าสุด", "อุปกรณ์ที่คืนล่าสุด", "วันที่คืนล่าสุด", "สภาพอุปกรณ์ล่าสุด"
                }
            ) {
                boolean[] canEdit = new boolean [] {
                    false, false, false, false
                };
     
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            jScrollPane1.setViewportView(jTable1);
     
            jButton2.setFont(new java.awt.Font("TH SarabunPSK", 0, 24)); // NOI18N
            jButton2.setText("Print");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(85, 85, 85)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(72, Short.MAX_VALUE))
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(108, 108, 108)
                    .addComponent(jButton1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(99, 99, 99))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(57, 57, 57)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton1)
                        .addComponent(jButton2))
                    .addContainerGap(40, Short.MAX_VALUE))
            );
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(147, 147, 147)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(83, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(59, 59, 59)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            WelcomeActionPerform(evt);
            setVisible(false);
        }                                        
     
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
           // TODO add your handling code here     
         jButton2.addActionListener(this);
        }                                        
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see [url=http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html]How to Set the Look and Feel (The Java™ Tutorials > Creating a GUI With JFC/Swing > Modifying the Look and Feel)[/url] 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(History.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(History.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(History.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(History.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new History().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable jTable1;
        // End of variables declaration                   
     
        private void WelcomeActionPerform(ActionEvent evt) {
            new Welcome().setVisible(true);
        }
     
        public void actionPerformed(ActionEvent ignore){
           MessageFormat header = new MessageFormat("Page {0,number,integer}");
           try
           {
             jTable1.print(JTable.PrintMode.FIT_WIDTH,header,null);          
           }catch(java.awt.print.PrinterException e)
           {
               System.err.format("Can not print %s%n",e.getMessage());
           }
        }
    }

    Thank you in advance
    Last edited by tawisak; October 15th, 2012 at 02:53 AM.


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 262 Times in 231 Posts

    Default Re: how to print a Jtable that retrieves data from the database.

    java.lang.ArrayIndexOutOfBoundsException: 18

    The code tries to access element number 18 of an array that does not have an element number 18.

    Now you look in the code and determine where this is taking place and why. Use System.out.println(myVariables) to see what the variables contain. In a case such as this, a System.out.println(myArray.length + "") might be of use. There are only so many arrays in so many lines of code, one of them has to be the bad one. Compare what you find to the error message and hopefully this will help you understand what the error message is trying to tell you too.

Similar Threads

  1. how to embed combobox,checbox in JTable read write to database
    By scorpion.poison in forum JDBC & Databases
    Replies: 1
    Last Post: August 30th, 2012, 12:53 AM
  2. Data from .txt to JTable?
    By skywire_ in forum File I/O & Other I/O Streams
    Replies: 3
    Last Post: September 19th, 2011, 04:00 AM
  3. refreshing a jtable with database
    By kollyisrealisaac in forum JDBC & Databases
    Replies: 0
    Last Post: May 7th, 2011, 01:50 PM
  4. How to print out data from web page to printer????
    By verma86 in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: April 2nd, 2010, 10:26 PM
  5. Java Swing Tables ( JTable Models ) to connect to Database
    By javaprogrammer in forum JDBC & Databases
    Replies: 0
    Last Post: January 26th, 2010, 03:13 PM

Tags for this Thread