Search code examples
javamysqlswingjtablejtableheader

How to insert data into swing table whose columns are dynamically defined (data from a mysql database)?


I have a table and on a opening of a frame the table receives its columns and their respective headers from a table in mysql database. How can i insert all the values from the sql database table into the swing table?? Here is my code...

DefaultTableModel dtm=(DefaultTableModel)jTable1.getModel();
String query1=null;
try    {
  query1="select * from "+Variables.table+";";
  ResultSet rsft=st.executeQuery(query1);  
  Object o[]=new Object[x];  
  while(rsft.next()) {                
    for(int i=1;i<=x;i++){
      o[i-1]=rsft.getString(i);
    }
    dtm.addRow(o);
  }
} catch(Exception e) {
  System.out.println(e.getMessage());  
}

In above code x is an integer denoting the number of colums in sql table. And Variables.table is a static variable containing the table name. Thank You


Solution

  • The problem is that getColumnCount will still return 0, despite that you added some rows. Just call setColumnCount as well.

    You can verify this in the source code, or just perform a quick test, e.g.

    import javax.swing.table.DefaultTableModel;
    
    public class DefaultTableModelDemo {
      public static void main( String[] args ) {
        DefaultTableModel defaultTableModel = new DefaultTableModel();
        defaultTableModel.addRow( new Object[]{"Test", "Test"} );
        System.out.println( "defaultTableModel.getRowCount() = " + 
           defaultTableModel.getRowCount() );
        System.out.println( "defaultTableModel.getColumnCount() = " + 
           defaultTableModel.getColumnCount() );
      }
    }
    

    gives the following output

    defaultTableModel.getRowCount() = 1
    defaultTableModel.getColumnCount() = 0
    

    It might be easier to just create a data vector first, and then create a new TableModel and replace the existing TableModel of the JTable.

    Further remarks:

    • Since the dtm is already used for a JTable, you should only update it on the Event Dispatch Thread. But database connections/queries are typically "slow" and should not be performed on the EDT. You can avoid this by either wrap each of the addRow calls in a SwingUtilities#invokeXXX call or just construct a new TableModel on the background thread and replace the model in one go on the EDT. Consult the Swing concurrency tutorial for more information.
    • Do not forget to close the ResultSet in a finally block