-1

I am trying to populate data in a JTable with a DefaultTableModel from a MySQL database using the addRow function but somehow it's not working. The data is not getting populated in the table model. I am sharing my code please help me with that,

inventoryTable = new JTable();


        String showquery="select * from sample.inventory where parts='BSP'";
        PreparedStatement showPst;

        DefaultTableModel showTable=new DefaultTableModel();
        inventoryTable.setModel(showTable);
        try{
            showPst=connect.prepareStatement(showquery);
            //showPst.setString(2, "BSP");
            ResultSet showrs=showPst.executeQuery();
            ResultSetMetaData meta=(ResultSetMetaData) showrs.getMetaData();
            String[] rowdata=new String[2];
        while(showrs.next()){
                rowdata[0]=showrs.getObject(2)+" "+showrs.getObject(3)+" "+showrs.getObject(5)+" "+showrs.getObject(8)+" "+showrs.getObject(7);
                rowdata[1]=(String) showrs.getObject(15);

                showTable.addRow(rowdata);
        }

        }catch(Exception e){
            e.printStackTrace();
        }
        inventoryTable.setModel(showTable);
        showTable.fireTableDataChanged();
    inventoryTable.setBounds(62, 0, 489, 306);
    panel.add(inventoryTable);
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

2

A table has rows and columns. A bit of simple debugging could have shown you that your table model lacks columns:

  public static void main(String[] args) {
    DefaultTableModel tableModel = new DefaultTableModel();
    tableModel.addRow(new Object[]{"Test", "Test"});
    System.out.println(tableModel.getRowCount());//returns 1
    System.out.println(tableModel.getColumnCount());//returns 0
  }

As long as the table has zero columns, no data will be displayed. You can for example use the

public DefaultTableModel(Vector columnNames, int rowCount)

constructor to specify the column names.

Robin
  • 36,233
  • 5
  • 47
  • 99