1

I'm working with a JTable, whose cells data are contained in Object. One column shows a float number. I want to GET the value into afloat, limit decimal places to 3, and then I want to reload the correct data in the cell, so I want to SET the value into the cell again. The problem appears in the last conversion:

 private class CambioTablaMeasurementListener implements TableModelListener{

    public void tableChanged(TableModelEvent e){
        try{
            if(sendDataToDisp){
                TableModel model = (TableModel)e.getSource();
                float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));
               // Now i want to limit to only 3 decimal places, so:

                double aux = Math.round(value*1000.0)/1000.0;
                value = (float) aux;
                Float F = new Float(value);

                // Now i want to load data back to the cell, so if you enter 0.55555, the cell shows 0.555. This Line gives me an exception (java.lang.Float cannot be cast to java.lang.String):
                model.setValueAt(F, e.getLastRow(), 1);

                // Here I'm getting another column, no problem here:
                String nombreAtributo = (String)model.getValueAt(e.getLastRow(), 0);
                nodoAModificar.setCommonUserParameter(nombreAtributo, value);

            }
           ...}
insumity
  • 5,311
  • 8
  • 36
  • 64
Roman Rdgz
  • 12,836
  • 41
  • 131
  • 207

2 Answers2

2

You need to convert Float instance to String.

model.setValueAt(F.toString(), e.getLastRow(), 1);

or

model.setValueAt(String.valueOf(F), e.getLastRow(), 1); // preferred since it performs null check
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
2

You can use DecimalFormat to display a float as a String in a given format:

...
float value = Float.parseFloat((String)model.getValueAt(e.getLastRow(), 1));             
DecimalFormat dec = new DecimalFormat("#.###");
model.setValueAt(dec.format(value), e.getLastRow(), 1);
...
Fortega
  • 19,463
  • 14
  • 75
  • 113
  • Still getting an exceptión. A really long one, Eclipse doesn't show which one it is because it's really long. – Roman Rdgz Jun 21 '11 at 09:54
  • I have been able to check which exception it is: java.lang.StackOverflowError again – Roman Rdgz Jun 21 '11 at 10:28
  • 2
    Possibly because the setValueAt triggers another tableChanged() event? – Fortega Jun 21 '11 at 10:51
  • OK, I realised that changing the value is getting me into the Listener function again and again, but that's is a different problem I asked in http://stackoverflow.com/questions/6424144/java-stackoverflowerror Thanks everybody, I'll close this question – Roman Rdgz Jun 21 '11 at 10:57