The truth is that neither your question, nor the way it exists to change the data of a JTable
are too clear, but let's try it.
Here you have an MVCE so you can modify it as you need. (comments in the code) that allows the change of data and recalculates the 3rd column depending on the first two as requested.
NOTES:
- I have done the tests in Eclipse: keep in mind that the IDE (in your case NetBeans) does not influence how the technologies work (in this case Swing).
- I have done the operation of
precio * cantidad
, but move to discount as you want is very easy ...
MVCE
public static void main(String[] args) throws Exception {
// nombre de las columnas
Object nombreColumnas[] = { "Precio" , "Cantidad", "Total" };
// datos iniciales SIN TOTALES
String datos[][] = {
{ "10.33", "2", "" },
{ "30.5", "8", "" } };
// creamos la tabla con los datos de ejemplo
final JTable table = new JTable(datos, nombreColumnas);
// calculamos los totales antes de mostrar la tabla
table.setModel(calculatTotales(table.getModel()));
// y le añadimos un listener
//
// ¡¡¡¡OJO!!!!!
//
// El listener se lo ponemos AL MODELO DE DATOS, no a la tabla!!!!
table.getModel().addTableModelListener(new TableModelListener() {
// para evitar concurrencias
boolean active = false;
// evento general
public void tableChanged(TableModelEvent e)
{
// si no tiene una ejecucion y hemos modificado
if (!active && e.getType() == TableModelEvent.UPDATE) {
active = true;
// recogemos el modelo
TableModel modelo = table.getModel();
// y le ponemos el nuevo con los totales calculados
table.setModel(calculatTotales(modelo));
active = false;
}
}
});
// jframe standard para enseñar la tabla
JFrame frame = new JFrame();
frame.setSize(300, 100);
// apartde de hacer scrill sirve para
// mostrar los titulos de las columnas
frame.add(new JScrollPane(table));
frame.setVisible(true);
}
private static TableModel calculatTotales(TableModel datos) {
for (int x = 0; x < datos.getRowCount(); x ++) {
String valor = null;
try {
valor = String.valueOf((Double.valueOf((String) datos.getValueAt(x, 0)) * (Integer.valueOf((String) datos.getValueAt(x, 1)))));
} catch (Exception e) {}
datos.setValueAt(valor, x, 2);
}
return datos;
}
RESULT:
Initial
once modified