Pages

September 23, 2010

JTable with JDBC or Hibernet result set | Example

Rendering JDBC or Hibernate result set data with JTable , is some what difficult to implement with JTables’s Data Model.
Here, in this post i have shared my code.
   1:  /*    creates JTable & Data Model ,displays Database result set in JTable.
   3:        @author piyushnp 
   5:        $24-01-2010
   6:  */
   7:   
   8:  public void initMyJTable()            
   9:  {    
  10:   
  11:        private javax.swing.JTable jTable1;
  12:   
  13:        jTable1 = new javax.swing.JTable();
  14:        jTable1.setModel(tmodel);
  15:        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
  16:        jTable1.setRowMargin(3);
  17:        jScrollPane1.setViewportView(jTable1);
  18:   
  19:        /* ans is list of Objects of YourDatabeTableClassName */
  20:        List<YourDatabeTableClassName> ans=null; 
  21:        Iterator <YourDatabeTableClassName> iterator=null;
  22:        
  23:        /* table model used to for data*/
  24:        TableModel tmodel; 
  25:        int tableRowCount;
  26:   
  27:        /* store List of Objects into ans */   
  28:        ans=sDao.getWeightMaster();     
  29:   
  30:        /* stores tabel data */  
  31:        Vector tableData = new Vector();   
  32:        Vector<String> tableHeaders = new Vector<String>();    
  33:        
  34:        tableHeaders.add("Serial No");
  35:        tableHeaders.add("Ticket No");
  36:        tableHeaders.add("Vehicle No");
  37:                      
  38:        for(Object o : ans) 
  39:        {    
  40:            YourDatabeTableClassName w = (YourDatabeTableClassName)o;
  41:            Vector<Object> oneRow = new Vector<Object>();
  42:           
  43:            oneRow.add(w.getId().getSrNo());
  44:            oneRow.add(w.getId().getTicketNo());
  45:            oneRow.add(w.getVehicleNo());
  46:           
  47:            tableData.add(oneRow);
  48:        }
  49:        tableRowCount=tableData.size();    
  50:        
  51:        /* creates TabelModel with JTable's DATA and HEADER Vectors */
  52:        tmodel=new DefaultTableModel(tableData, tableHeaders);  
  53:      
  54:    }

No comments:

Post a Comment