JTable: calculate result from 2 cells and put it in another cell

hi,

I have implemented this method in my JTable variant:

publicvoid tableChanged(TableModelEvent e){

int column = e.getColumn();

DefaultTableModel model = (DefaultTableModel)e.getSource();

if (model.getRowCount() > 0 && column > 0)

{

double pos = (Double)model.getValueAt(1, column);

double neg = (Double)model.getValueAt(2, column);

double res = pos - neg;

((Vector)model.getDataVector().elementAt(3)).setElementAt((Double)res, column);

}

else

super.tableChanged(e);

}

it is pretty obvious what it tries to do.

However, the result in the 3rd row is updated only when I click with my mouse on that row (any cell of that row). Why?

Is there a better way to implement what I am trying to do?

[1183 byte] By [xpantaa] at [2007-11-27 9:21:58]
# 1
((Vector)model.getDataVector().elementAt(3)).setElementAt((Double)res, column);Not the standard way to do things. Try this.model.setValueAt( (Double)res, 3, column );ICE
icewalker2ga at 2007-7-12 22:16:10 > top of Java-index,Desktop,Core GUI APIs...
# 2

> Is there a better way to implement what I am trying to do?

Your solution is close, but you should never update the data vector directly. All changes to the data should be done through the TableModel. The TableModel will then fire the appropriate event to make sure the table repaints itself. So basically use the setValueAt(...) method as suggest above.

camickra at 2007-7-12 22:16:10 > top of Java-index,Desktop,Core GUI APIs...
# 3

To be honest, I had tried the .setValueAt() method but I got the feeling that setValueAt() triggers tableChanged() and so I got a StackOverFlowError like the following:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

at java.lang.Double.<init>(Unknown Source)

at java.lang.Double.valueOf(Unknown Source)

at com.client.EfedreiesJTable.tableChanged(EfedreiesJTable.java:55)

at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)

at javax.swing.table.AbstractTableModel.fireTableCellUpdated(Unknown Source)

at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)

at com.client.EfedreiesJTable.tableChanged(EfedreiesJTable.java:55)

(... and so on...)

That is why I tried to insert directly to the Data Vector...

xpantaa at 2007-7-12 22:16:10 > top of Java-index,Desktop,Core GUI APIs...
# 4
Solved!I changed the "If" line into this:if (model.getRowCount() > 0 && column > 0 && (row == 1 || row == 2))and it worked.
xpantaa at 2007-7-12 22:16:10 > top of Java-index,Desktop,Core GUI APIs...