Search code examples
javaswingjtableindexoutofboundsexception

PLease assist with my JTable Loop Exception


Here is my code where I'm trying to loop through all the rows in my new stock table. Even when I use totalRows - 1 I still get the same exeption. Any help will be appreciated.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
int totalRows = newTable.getRowCount();
String tempName = "";
int tempTotal = 0;
System.out.println("total new rows: " + totalRows);

    try {
        for (int i = 0; i < (totalRows - 1); i++) {
            tempName = currentTable.getModel().getValueAt(i, 0).toString();
            tempTotal = Integer.parseInt(currentTable.getModel().getValueAt(i, 1).toString());
            System.out.println("Current Table Product:    " + currentTable.getModel().getValueAt(i, 0).toString());
            System.out.println("Current Table Total:  " + currentTable.getModel().getValueAt(i, 1).toString());

            System.out.println("New Table Product:    " + newTable.getModel().getValueAt(i, 0).toString());
            System.out.println("New Table Temp Total:  " + newTable.getModel().getValueAt(i, 1).toString());

            //if (newTable.getModel().getValueAt(i, 0).toString() == currentTable.getModel().getValueAt(i, 0).toString()) {
            //    int newTempTotal = Integer.parseInt(newTable.getModel().getValueAt(i, 1).toString());
            //    newTotal = newTempTotal + tempTotal;
            //    System.out.println("product:    " + newTable.getModel().getValueAt(i, 0).toString());
            //    System.out.println("grand new total:    " + newTotal);
            //}
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

Then I get the following exception...

java.lang.ArrayIndexOutOfBoundsException: 3 >= 3
at java.util.Vector.elementAt(Vector.java:477)
at javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:648)
at great.meat.AddNewStock.jButton1ActionPerformed(AddNewStock.java:325)
at great.meat.AddNewStock.access$300(AddNewStock.java:23)
at great.meat.AddNewStock$4.actionPerformed(AddNewStock.java:210)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

Solution

  • I don't know how many rows both tables have, but your problem could be in this line:

    tempName = currentTable.getModel().getValueAt(i, 0).toString();
    

    because you are looping using the newTable row count:

    int totalRows = newTable.getRowCount();
    

    but you're trying to get the data from currentTable. If currentTable has less rows than newTable then it will throw an exception.