Search code examples
javaswingjtabledefaulttablemodel

Java DefaultDataTable dynamic values


I have a JTable i would like to fill using the DefaultTableModel unfortunately my output comes as arrays and not as new rows as i would like them to. Please see my code below and do ask if any further explanation is needed! :)

dataTable.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {
                    DatabaseInteraction.getCityInfo("").get("datas").toArray()

            },
                    DatabaseInteraction.getCityInfo("").get("columns").toArray()));

Database interaction function here:

public static Map<String,List<String>> getCityInfo(String query )
{
    if(query.isEmpty()){
        query = "SELECT * FROM "+ database+ "." +table;
    }

    try {
        Statement stmt = getConn().createStatement();
        ResultSet rs;
        rs = stmt.executeQuery(query);
        ResultSetMetaData rsmd = rs.getMetaData();


        //Get Column names
        List<String> cNames = new ArrayList();
        List<Object> results = new ArrayList<Object>();

        for (int i = 1; i <= rsmd.getColumnCount(); i++){
            cNames.add(rsmd.getColumnName(i));
        }

        //Get Data
        while (rs.next()) {
            List<String> tempResults = new ArrayList();

            for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                tempResults.add(rs.getString(i));

                if(i == rsmd.getColumnCount()){
                    results.add(tempResults);

                }

            }
        }


        HashMap map =new HashMap();
        map.put("columns",cNames);
        map.put("datas",results);
        System.out.println(map);
        return map;

    }

The output i get in my console is: {columns=[username, password, free], datas=[[hej, hej, 1], [Brugernavn, Password, 1], [Brugernavn1, Password, 0], [test1, test2, 1], [, , 1]]} Which looks fine to me but as i said earlier it just get append it as arrays and not one array - new row.


Solution

  • I suggest you to create your own DefaultTableModel by using Vectors. You can use something like that:

    public static DefaultTableModel createModel(ResultSet rs){
       DefaultTableModel dtm = new DefaultTableModel();
       Vector rowVectors = new Vector();
       Vector columnHeaderVector = new Vector();
    
         //To get rows correctly
         int columncount = rs.getMetaData().getColumnCount();
    
         //Iterating all data and creating rows vector
         while(rs.next())
         {
             //It seems confusing to newbies,
             //for defaultTableModel we need a vector containing rows(as a vector)
             Vector singleRow = new Vector();
             for(int i=1;i<=columncount;i++)
             {
                 singleRow.addElement(rs.getObject(i));
             }
             rowVectors.addElement(singleRow);
         }
    
         //Creating header for table
         for(int i=1;i<=columncount;i++)
         {
             columnHeaderVector.addElement(rs.getMetaData().getColumnName(i));
         }
    
       //Setting vectors to the model
       dtm.setDataVector(rowVectors, columnHeaderVector);
       return dtm;      }
    

    IN YOUR MAIN METHOD OR WHERE YOU CREATE JTable

    ResultSet rs;
    rs = stmt.executeQuery(query);
    DefaultTableModel dtm = createModel(rs);
    dataTable.setModel(dtm);
    

    There may be some errors I wrote it here and should be try/catch block too, but you can fix and add them :)