Search code examples
javaswingjtableclasscastexceptiondefaulttablemodel

Unable to use DefaultTableModel in JTable


Object rowData[][] = {
        {1, "", null, "", "", false, ""},
        {2, "", null, "", "", false, ""},
        {3, "", null, "", "", false, ""},
        {4, "", null, "", "", false, ""},
        {5, "", null, "", "", false, ""},
        {6, "", null, "", "", false, ""}
    };

    DefaultTableModel model = new DefaultTableModel() {
        @Override
        public Class<?> getColumnClass(int columnIndex) {
            switch (columnIndex) {
                case 0:
                    return Integer.class;
                case 1:
                    return String.class;
                case 2:
                    return Integer.class;
                case 3:
                    return String.class;
                case 4:
                    return String.class;
                case 5:
                    return Boolean.class;
                case 6:
                    return String.class;
                default:
                    return super.getColumnClass(columnIndex);
            }
        }
    };
    model.addColumn("Sr No.");
    model.addColumn("Name");
    model.addColumn("Age");
    model.addColumn("Gender");
    model.addColumn("City");
    model.addColumn("isChild");
    model.addColumn("Address");
    model.addRow(rowData);

    JTable table = new JTable(model);
    table.setRowHeight(20);
    table.setRowMargin(2);
    table.getColumnModel().getColumn(0).setMaxWidth(50);

    TableColumn childColumn = table.getColumnModel().getColumn(5);
    JCheckBox childBox = new JCheckBox();
    childColumn.setCellEditor(new DefaultCellEditor(childBox));

I have written above code to display a table to user and the second last column needs to be a check box. So I Googled and found the below code after picking small small part from many sources, but I am getting below exception:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:     
   [Ljava.lang.Object; cannot be cast to java.lang.Boolean

And when I change Boolean.class to String.class in switch case it didn't show any exception but I am getting values in row as java.lang.String etc

As I am new to JFrame, JTable etc. I am not able to identify what I am doing wrong. Why the ClassCastException and how to fix it?


Solution

  • The DefaultTableModel.addRow(Object[]) can only add a single row. But what you are trying to do is add multiple rows.

    Iterate over the rows and add each separately.

    Replace model.addRow(rowData); with:

    for (Object[] row : rowData) {
        model.addRow(row);
    }