Search code examples
javaswingarraylistjtabledefaulttablemodel

How to read specific colum in JTable?


I have a Table called PRODUCT(item,qty,price for 1Kg,amount) after i added data into table i want to get total amount of amount column. So I know how to read all data from table. But i don't know how to read and add one field

here's my code:

    DBconnector db = new DBconnector();
    db.connect();          

    DefaultTableModel dtm = (DefaultTableModel) tblOrder.getModel();
    int numRow = dtm.getRowCount();//get rows
    int numCol = dtm.getColumnCount();//get colums

    ArrayList<Object> list = new ArrayList<Object>();

    for (int i = 0 ; i < numRow ; i++){
         for (int j = 0 ; j < numCol ; j++){
            list.add(tblOrder.getValueAt(i, j));  
        }
                   System.out.println(list);
        }

Anyone please can help me to do this?


Solution

  • I will assume your column 'amount' contains numbers, without a currency (so 5.12 instead of $5.12)

    int numRow = dtm.getRowCount();
    int columnAmount = 3; // TODO Set this to the correct column.
    double totalAmount = 0.0;
    for (int i = 0; i < numRow; i++) { // Loop over all rows
        // Add the value from column 'amount' to the total:
        totalAmount += Double.parseDouble(tblOrder.getValueAt(i, columnAmount).toString());
    }
    
    // TODO Do something with totalAmount
    System.out.println(totalAmount);