I have a JTable where i enter some values. This is the listener function to know if it has been made any change at the values, so i can update them. Values must have the format indicated (#.###), so I’m doing this fix to round the float to 3 decimal places if the client enter more than 3.
private class CambioTablaPretratamientoListener implements TableModelListener{
public void tableChanged(TableModelEvent e){
try{
if(enviarDatosADispositivo){
TableModel model = (TableModel)e.getSource();
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
DecimalFormat dec = new DecimalFormat("#.###");
String aux = dec.format(value);
if(model.getValueAt(e.getLastRow(), 1).equals(aux))
return;
else
model.setValueAt(aux, e.getLastRow(), 1);
value = Float.parseFloat(aux);
String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);
}
}catch(BusinessException ex){
ex.printStackTrace();
}
}
}
Code seems to work at first, because it rounds and the number appears in the table, but the value is not getting updated. I guess I’m doing something wrong with the DecimalFormat, because if I leave the function like this one, it works:
private class CambioTablaPretratamientoListener implements TableModelListener{
public void tableChanged(TableModelEvent e){
try{
if(enviarDatosADispositivo){
TableModel model = (TableModel)e.getSource();
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
nodoAModificar.setPretratamientUserParameter(nombreAtributo, value);
}
}catch(BusinessException ex){
ex.printStackTrace();
}
}
}
And finall
If you use BigDecimal, you could actually truncate the numbers, instead of trying to use Float’s (lack of) precision.