Reputation: 462
I got a problem I can't resolve alone and with help of other topics there. Found some 1 pretty similar but it hasn't help.
My problem is kind of tricky ones I think, I'll try to explain this as good as I can.
So, I got a JTable with couple of columns, column 2 and 3 are editable and column 4 is a product of these two (col4 = col2*col3). What I am going to do is when I edit column 2 or 3, column 4 will automaticly update it's value. I acomplished that but not fully. The cell is updating only when I finish editing by mouseclick. I'd like to cell react with same way if editing is finished by ENTER key.
I was trying a little bit with:
if(recipeTable.getCellEditor()!=null)recipeTable.getCellEditor().stopCellEditing();
but it isn't changing anything.
Here is my code:
recipeTableModel = new DefaultTableModel(COLUMN_HEADLINE, 0) {
@Override
public boolean isCellEditable(int row, int column)
{
model.updateTotalPriceInTable(recipeTable);
return (column == 2) || (column == 3);
}
};
And:
public void updateTotalPriceInTable(JTable table)
{
double totalPrice;
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
for(int i = 0; i < tableModel.getRowCount(); i++)
{
totalPrice = Double.parseDouble(tableModel.getValueAt(i, 2).toString()) * Double.parseDouble(tableModel.getValueAt(i, 3).toString());
tableModel.setValueAt(totalPrice, i, 4);
}
tableModel.fireTableDataChanged();
}
~~~~~~~~~~~~~~~~~~~~~~~~ Ok I figured it out, that is code the code that resolved my problem:
@Override
public void setValueAt(Object aValue, int row, int column)
{
Vector rowVector = (Vector)dataVector.elementAt(row);
rowVector.setElementAt(aValue, column);
rowVector.setElementAt(Double.parseDouble((String) rowVector.get(2))*Double.parseDouble((String) rowVector.get(3)), 4);
fireTableDataChanged();
}
Upvotes: 0
Views: 69
Reputation: 324098
Override the setValueAt(...)
method of your TableModel. You invoke super.setValueAt(...) to save the data normally.
Then whenever the data in column 2 or 3 changes, you then calculate the value of column 4 and update the model.
Upvotes: 2