"Can not format given Object as a Number" when displaying JTable

1

Greetings, I have a problem when showing the contents of a database in a JTable table, in a .java project using netbeans.

I tried to observe the output of the column with which I get an error, it is the 5th column a data of type Float, the 4th position of the String [], and the data that it returns to me is correct ....

With what I can not know why I'm aborted with this error:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number
at java.text.DecimalFormat.format(DecimalFormat.java:507)
at java.text.Format.format(Format.java:157)
at javax.swing.JTable$DoubleRenderer.setValue(JTable.java:5356)
at javax.swing.table.DefaultTableCellRenderer.getTableCellRendererComponent(DefaultTableCellRenderer.java:257)
at javax.swing.JTable.prepareRenderer(JTable.java:5723)
at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
at javax.swing.JComponent.paintComponent(JComponent.java:780)
at javax.swing.JComponent.paint(JComponent.java:1056)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JViewport.paint(JViewport.java:728)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paint(JComponent.java:1065)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:586)
at javax.swing.JComponent.paintChildren(JComponent.java:889)
at javax.swing.JComponent.paintToOffscreen(JComponent.java:5217)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(RepaintManager.java:1579)
at javax.swing.RepaintManager$PaintManager.paint(RepaintManager.java:1502)
at javax.swing.RepaintManager.paint(RepaintManager.java:1272)
at javax.swing.JComponent.paint(JComponent.java:1042)
at java.awt.GraphicsCallback$PaintCallback.run(GraphicsCallback.java:39)
at sun.awt.SunGraphicsCallback.runOneComponent(SunGraphicsCallback.java:79)
at sun.awt.SunGraphicsCallback.runComponents(SunGraphicsCallback.java:116)
at java.awt.Container.paint(Container.java:1975)
at java.awt.Window.paint(Window.java:3904)
at javax.swing.RepaintManager$4.run(RepaintManager.java:842)
at javax.swing.RepaintManager$4.run(RepaintManager.java:814)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:814)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:789)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:738)
at javax.swing.RepaintManager.access$1200(RepaintManager.java:64)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1732)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

This is the code that I am using, specifically a method that I call it in the window's constructor, which fills in the List with the data of the database ..

private void rellenaListado() {
    //Pido a la base de datos los datos de la tabla articulo
    DefaultTableModel dtm = devuelveDTM();

    //Pido a la base da datos los datos de la tabla articulo
    String[] datos = new String[dtm.getColumnCount()];

    //Crear un objeto DataBase
    DataBase db = new DataBase();

    //Crear un objeto ResultSet y lo inicializamos a null
    ResultSet rs = null;

    try {
        //Abrimos la conexión
        db.abrirConexion();
        //Creamos la consulta
        String consulta = "SELECT * FROM articulo;";
        //Ejecutamos la consulta, para eso necesitamos un objeto ResultSet
        rs = db.ejecutaConsulta(consulta);
        while (rs.next()) {
            //Recorro el ResultSet
            datos[0] = rs.getString(1);
            datos[1] = rs.getString(2);
            datos[2] = Integer.toString(rs.getInt(3));
            datos[3] = Integer.toString(rs.getInt(4));
            datos[4] = String.format("%5.2f", rs.getFloat(5));
            dtm.addRow(datos);
        }
    } catch (MyException | SQLException ex) {
        VentanaNotificaciones.ventanaError(ex.getMessage(), padre);
    } finally {
        try {
            if (rs != null) {
                //Cierro el ResultSet
                db.cierraResult(rs);
            }
            //Cierro la conexión con la base de datos
            db.cerrarConexion();
        } catch (MyException ex) {
            VentanaNotificaciones.ventanaError(ex.getMessage(), padre);
        }
    }
}

I have checked the outputs with these sneaks but I get the content of the correct table ...

            //Comienzo de pruebas (chivatos)
            System.out.println("Pos 0 Array:" + datos[0]);
            System.out.println("Pos 1 Array:" + datos[1]);
            System.out.println("Pos 2 Array:" + datos[2]);
            System.out.println("Pos 3 Array:" + datos[3]);
            System.out.println("String.format:" + String.format("%5.2f", rs.getFloat(5)));
            System.out.println("rs.getFloat(5):" + rs.getFloat(5));

            String s = String.format("%5.2f", rs.getFloat(5));
            String replace = s.replace(" ","");
            datos[4] = String.format("%5.2f", replace);

            System.out.println("Pos 4 Array:" + datos[4]);

The column that presents problems is the following, if I comment the line does not abort but, and obviously it does not show the price of type float:

datos[4] = String.format("%5.2f", rs.getFloat("5"));

Thank you all in advance, and see if you can throw a cable.

    
asked by HectorCG 22.04.2017 в 23:29
source

1 answer

2

If the exception message says:

  

Can not format given Object as a Number

That means that in the data model ( javax.swing.table.TableModel ) it is being defined that a certain type of data will be received in a certain column. However, the data in the model for that particular column does not contain that specific data type, but rather another type.

That is, the method getColumnClass of the model returns Double.class for that specific index:

public Class<?> getColumnClass(int columnIndex) {
    switch (columnIndex) {
        ...
        case 4:
            return Double.class;
        ...
    }
}

However, you are putting in that column a string, a String when you must put a Double or double . It is not possible to cast from String to Number .

There are two possible solutions: change the data type returned in getColumnClass to String.class or change the data type in the data (leave it as float ). In the latter case, would render with the default format and not with the format you have indicated ( "%5.2f" ).

.................................
For more information, see the section Concepts: Editors and Renderers in How to Use Tables inside The Java ™ Tutorials .

    
answered by 23.04.2017 / 00:41
source