0

Right now I have a JTable and whenever a button is pressed, it displays the item name and the item price from the MySql database that I had created. What I am having trouble with is to keep a running total for the price of the items on that are present on the table.

enter code here  private void waterbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
    try{
     st = connection.createStatement();   
    String query;
    query = "SELECT itemName, itemPrice FROM item WHERE itemID = '11111'";
    String itemName = " ",itemPrice =" ";  

      ResultSet rs = st.executeQuery(query);

       if(rs != null){
        while(rs.next())
        { 
         itemName = rs.getString(1);
         itemPrice = rs.getString(2);
        }
      model.addRow(new Object[]{itemName, itemPrice});

       }
       String holder = model.getValueAt(WIDTH, 1).toString(); 
       total += Double.parseDouble(holder);
       System.out.println(total);
         } catch (SQLException | NumberFormatException | ArrayIndexOutOfBoundsException ex) {}

The variable "total" is a global double and the variable "model" is a DefualtTableModel. Am I on the right track on getting this running total or should I try a completely different approach? Please help I am about at wits end.

JudgementFlame
  • 107
  • 1
  • 2
  • 9
  • 3
    Isn't `itemPrice` a numeric type? Why `getString`? Shouldn't `addRow` and the `total` be _in_ the loop? Please edit your question to include an [sscce](http://sscce.org/). – trashgod Apr 23 '13 at 01:58
  • 1
    What is WIDTH? Does that ever change or is it a hard-coded constant? Also why don't you just add itemPrice to the total, instead of reading it back from the model. – sreejit Apr 23 '13 at 07:30

1 Answers1

0

Use a loop to calculate the total

   int row;
   for(row= 0; row<=model.getRowCount(); row++){
   String holder = model.getValueAt(row, 1).toString(); // I do not know why you are writing WIDTH here. 

   total += Double.parseDouble(holder);
   System.out.println(total);
   }
Pranjal Choladhara
  • 845
  • 2
  • 14
  • 35