1

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)?

camickr
  • 321,443
  • 19
  • 166
  • 288
Arroiz
  • 13
  • 2
  • What type does `DbUtils.resultSetToTableModel()` return? Is it [`DefaultTableModel`](https://docs.oracle.com/javase/8/docs/api/javax/swing/table/DefaultTableModel.html)? – Abra Jul 30 '20 at 10:06
  • From what people say on internet, yes, it returns DefautTableModle – Arroiz Jul 31 '20 at 01:19

1 Answers1

0

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;
    }
};
camickr
  • 321,443
  • 19
  • 166
  • 288
  • But how do I override it if the JTable is created inside of a JInternalFrame Class and is auto-created by netbeans? – Arroiz Aug 07 '20 at 00:46
  • I don't use an IDE to generate my code so I can't help. I prefer to spend my time learning Java/Swing, not the IDE. Then my code can be maintained in any IDE. My advice is don't use the IDE to generate your code. Just use the IDE to organize your classes and for debugging. – camickr Aug 07 '20 at 00:53