javadatabaseswingjtabletablemodel

How to define the JTable's Column's data type the same as MySql database?


I have created a graphical interface in Netbeans where I inserted a JTable inside a FORM JFrame. I have a MySql database and it's columns are:

Id: Integer

Name: String

Active: Boolean

However, when I use: jTable.setModel (DbUtils.resultSetToTableModel ()) (method of the library RS2XML.jar), the JTable is filled all as String.

How do I make JTable filled with the correct data types just like the database (Integer, String and Boolean)?


Solution

  • the JTable is filled all as String.

    The model should contain data of the proper type. The problem is you have mot defined what the data type should be for each column, so by default it is treated as Object and the default renderer will just invoke the toString() method on the object.

    You can override the getColumnClass(...) method of the JTable.

    Something like:

    JTable table = new JTable(model)
    {
        //  Returning the Class of each column will allow different
        //  renderers and editors to be used based on Class
    
        @Override
        public Class getColumnClass(int column)
        {
            for (int row = 0; row < getRowCount(); row++)
            {
                Object o = getValueAt(row, column);
    
                if (o != null)
                    return o.getClass();
            }
    
            return Object.class;
        }
    };