java - Calculate the subtotal while every time adding a new row in JTable -


how calculate subtotal while every time adding new row in jtable?

defaulttablemodel model = (defaulttablemodel) jtable1.getmodel();  int = 0; double total123 = 0.0; int row = model.getrowcount(); payment pm = new payment();  double sub_total123;  //calculate sub_total;;; sub_total123 = double.parsedouble(unit_price.gettext()) * integer.parseint(order_quantity.gettext()); pm.setsub_total(sub_total123);  sub_total.settext(double.tostring(pm.getsub_total()));  if (row < 10) {     model.addrow(new object[]{product_id.gettext(), product_name.gettext(),         integer.parseint(order_quantity.gettext()), double.parsedouble(unit_price.gettext()),         double.parsedouble(sub_total.gettext())}); }  (i = 0; < row; i++) {     total123 += ((double) jtable1.getvalueat(i, 4)).doublevalue();     total.settext(double.tostring(total123)); } 

i new jtable. while adding 1st row, wont sub total value , display in text field. when adding second row sub total value , insert text field , while adding 3rd row, start calculate sub total of 2nd row , 3rd row, wont include 1st row. how can achieve this?

there number of ways , come down requirements how achieve it, mind, want minimize number of iterations need perform on table each time new row added...

there's no point iterating on entire table if 1 row added, example. it's inefficient.

instead, use tablemodellistener , listen updates table model , update running total (adding new row values running total).

enter image description here

import java.awt.borderlayout; import java.awt.component; import java.awt.dimension; import java.awt.eventqueue; import java.awt.gridbagconstraints; import java.awt.gridbaglayout; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.text.numberformat; import javax.swing.jbutton; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jscrollpane; import javax.swing.jtable; import javax.swing.uimanager; import javax.swing.unsupportedlookandfeelexception; import javax.swing.event.tablemodelevent; import javax.swing.event.tablemodellistener; import javax.swing.table.defaulttablecellrenderer; import javax.swing.table.defaulttablemodel;  public class subtotaltable {      public static void main(string[] args) {         new subtotaltable();     }      public subtotaltable() {         eventqueue.invokelater(new runnable() {             @override             public void run() {                 try {                     uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname());                 } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception ex) {                 }                  jframe frame = new jframe("testing");                 frame.setdefaultcloseoperation(jframe.exit_on_close);                 frame.setlayout(new borderlayout());                 frame.add(new testpane());                 frame.pack();                 frame.setlocationrelativeto(null);                 frame.setvisible(true);             }         });     }      public class testpane extends jpanel {          private jlabel subtotal;         private defaulttablemodel tablemodel;          private double runningtally = 0;          public testpane() {             setlayout(new borderlayout());              tablemodel = new defaulttablemodel(new object[]{"price"}, 0);             jtable table = new jtable(tablemodel);             table.getcolumnmodel().getcolumn(0).setcellrenderer(new currencyrenderer());             add(new jscrollpane(table));              jpanel panel = new jpanel(new gridbaglayout());             gridbagconstraints gbc = new gridbagconstraints();             gbc.gridx = 0;             gbc.weightx = 1;             jbutton charge = new jbutton("charge");             charge.addactionlistener(new actionlistener() {                 @override                 public void actionperformed(actionevent e) {                      double subtally = 0;                     double tally = runningtally;                      int rows = (int) (math.round(math.random() * 9) + 1);                     (int row = 0; row < rows; row++) {                          double amount = (math.random() * 99999) + 1;                         tablemodel.addrow(new object[]{amount});                         tally += amount;                         subtally += amount;                      }                      system.out.println("subtally = " + subtally);                     system.out.println("tally = " + tally);                  }             });             panel.add(charge, gbc);              gbc.gridx++;             gbc.weightx = 0;              subtotal = new jlabel(getrunningtallydisplayvalue());             panel.add(subtotal, gbc);              add(panel, borderlayout.south);              tablemodel.addtablemodellistener(new tablemodellistener() {                 @override                 public void tablechanged(tablemodelevent e) {                     switch (e.gettype()) {                         case tablemodelevent.delete:                             system.out.println("delete");                             break;                         case tablemodelevent.insert:                             system.out.println("insert");                             (int row = e.getfirstrow(); row <= e.getlastrow(); row++) {                                 object value = tablemodel.getvalueat(row, 0);                                 if (value instanceof double) {                                     runningtally += (double)value;                                 }                             }                             break;                         case tablemodelevent.update:                             system.out.println("update");                             break;                     }                     subtotal.settext(getrunningtallydisplayvalue());                 }             });         }          protected string getrunningtallydisplayvalue() {              return numberformat.getcurrencyinstance().format(runningtally);          }          @override         public dimension getpreferredsize() {             return new dimension(200, 200);         }     }      public class currencyrenderer extends defaulttablecellrenderer {          public currencyrenderer() {             sethorizontalalignment(jlabel.right);         }          @override         public component gettablecellrenderercomponent(jtable table, object value, boolean isselected, boolean hasfocus, int row, int column) {             if (value instanceof double) {                 value = numberformat.getcurrencyinstance().format(value);             }             super.gettablecellrenderercomponent(table, value, isselected, hasfocus, row, column);             return this;         }      } } 

take @ how use tables , in particular listening data changes


Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -