Hi, the problem with calculating the total amount, only the last amount is displayed from the list, it is necessary that everyone should be considered ... I will be grateful for the help

public void display() { defaultTableModel.getDataVector().removeAllElements(); //deleted defaultTableModel.fireTableDataChanged(); //deleted //создаем таблицу try { List<Record> records = RecordDao.getDao().queryForAll(); //запросить все данные из таблицы своей бд // перебираем все объекты и добавляем их втаблицу for (Record record : records) { if (employee.getId() == record.getEmployee_id()) { Object[] row = new Object[]{ record, // объект в целом employee.getName(), // из первой таблицы где только имена record.getMoney(), // выплаты DateUtils.convert(record.getDate()), // задали дату в приемлимый текст (07.02.12 15:34) }; defaultTableModel.addRow(row); jLabel.setText(String.valueOf("Общая сумма всех выплат: " + record.plusSum(record.getMoney()))); jLabel.setSize(150, 20); jLabel.setLocation(10, 220); jPanel.add(jLabel); } } } catch (SQLException e) { e.printStackTrace(); } } 

Method for adding in class Record

 public int plusSum(int allMoney){ allMoney = allMoney + money; return allMoney; } 
  • one
    And in the debugger what? Is jPanel.add generally called for each list item? - Vladimir Martyanov
  • Do not quite understand... ? - Andrey Gritsenko
  • In the debugger, how is the code executed? jPanel.add () is called for each list item? - Vladimir Martyanov

2 answers 2

You call the plusSum method on each Record, but you never save the result anywhere. You need to save the result somewhere. All sorts of options you can think of. The easiest way is to make the variable sum BEFORE the loop. Then in the loop do sum = record.plusSum(record.getMoney()) . When the cycle is completed, you will have the sum of all the records. Then this variable can only be output where you want. But this is just one of many options.

  • although, in this case, the plusSum method is generally not appropriate. easier to do sum + = record.getMoney () - Comfmore
  • that's right) thanks - Andrei Gritsenko
 jLabel.setText(String.valueOf("Общая сумма всех выплат: " + record.plusSum(record.getMoney()))); public int plusSum(int allMoney){ allMoney = allMoney + money; return allMoney; } 

I did not see here why the whole amount should be calculated. In plusSum you transfer payouts, add money with them and withdraw it. But nowhere do I see the preservation of the results of addition. Why do you think that the total amount should be calculated?