0
我在JTable中有金額列,並且有一個「總計」和「最終總計」按鈕。所以如果我把2和3放在數量欄中並且擊中'Total',那麼我在同一列的另一個單元中得到5(我的程序在這一步中工作正常)現在我想在5以下插入3和4。點擊'Final Total',然後想在最後一行的同一列(金額)中只顯示12(5 + 3 + 4)。 (5是我總得分的答案)。
在這裏我粘貼我的代碼'總'和'最終總計'按鈕。我不確定在「最終總計」按鈕中使用循環。所以請給它解決方案。如何計算JTable列的總數,但在特定索引處啓動
JButton total = new JButton("Total");
total.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag=1;
add.setEnabled(false);
Object source = ae.getSource();
if (source == total)
{
model.addRow(new Object[]{new Integer(0),"TOTAL",new Integer(1), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
for(i = 0; i < model.getRowCount(); i++)
{
amount = Double.parseDouble(model.getValueAt(i, 6).toString());
sum = new Double(sum+amount);
}
model.setValueAt(sum,model.getRowCount()-1,6);
}
JOptionPane.showMessageDialog(null,"If you pressed Total then you can't select 'Add Row' button ");
model.addRow(new Object[]{new Integer(0),"",new Integer(0), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
model.addRow(new Object[]{new Integer(0),"",new Integer(0), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
model.addRow(new Object[]{new Integer(0),"",new Integer(0), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
model.addRow(new Object[]{new Integer(0),"",new Integer(0), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
}
});
JButton btnFinalTotal = new JButton("Final total");
btnFinalTotal.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
flag=2;
Object source = ae.getSource();
if (source == btnFinalTotal)
{
d= Double.parseDouble(model.getValueAt(i,6).toString());
System.out.println("Current value of d is " +d);
model.addRow(new Object[]{new Integer(0),"FINAL TOTAL",new Integer(1), new Double(0.0),"",new Double(0.0),new Double(0.0),new Double(0.0),new Double(0.0)});
for(i=0;i>d;i++)
{
amount = Double.parseDouble(model.getValueAt(i, 6).toString());
finalamount= new Double(d+amount);
}
model.setValueAt(finalamount,model.getRowCount()-1,6);
}
}
});
public void tableChanged(TableModelEvent e)
{
if (e.getType() == TableModelEvent.UPDATE)
{
System.out.println("Cell " + e.getFirstRow() + ", "
+ e.getColumn() + " changed. The new value: "
+ table.getModel().getValueAt(e.getFirstRow(),
e.getColumn()));
int row = e.getFirstRow();
int column = e.getColumn();
if(flag==1)
{
if(column == 6)
{
// taxonamt= Double.parseDouble(model.getValueAt(row, 6).toString());
sum=Double.parseDouble(model.getValueAt(row, 6).toString());
// Double total = new Double (sum*(taxonamt/100));
Double total = new Double (sum);
model.setValueAt(total,model.getRowCount()-1,7);
}
}
}
}
都能跟得上表格模型 - 這東西你將不得不嘗試,你擁有關於問題的所有信息,我製作的任何解決方案或代碼最終都不會滿足您的所有需求/要求。過去我已經完成了它,並且浪費了幾天的時間 - 並且,SO不是代碼工廠。我的建議是,嘗試一下,您需要使用AbstractTableModel來支持您的自定義對象 – MadProgrammer