Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Error : javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel

Tags:

java

jtable

What I'm trying to do is I am creating a JTable inside a new instance of JPanel and JFrame and I am getting the error upon adding the rows in the table:

Object[] column = {"id", "title"};
Object[][] data = {};
JTable toDoTable = new JTable(data, column) {
  public Component prepareRenderer(TableCellRenderer renderer, int rowIndex,
      int columnIndex) {
       if(columnIndex == 1) {
          setFont(new Font("Arial", Font.BOLD, 12));
       } else {
           setFont(new Font("Arial", Font.ITALIC, 12));
       }

         return super.prepareRenderer(renderer, rowIndex, columnIndex);
  }
};


JScrollPane jpane = new JScrollPane(toDoTable);
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setSize(new Dimension(1100, 408));
frame.setTitle("JTable Font Setting Example");
panel.add(jpane);
frame.add(new JScrollPane(panel));
frame.setVisible(true);

// Add rows in the Table
DefaultTableModel model = (DefaultTableModel)toDoTable.getModel();
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
ResultSet rs = connServer.dbConnect();
  try
   {
      while (rs.next()) {
          String id = rs.getString("id");
          String title = rs.getString("title");
          model.addRow(new Object[]{id, title});
      }
    }
    catch(Exception e)
    {

    }

The error occurs in the add rows in table

like image 909
Yassi Avatar asked Feb 09 '23 08:02

Yassi


1 Answers

Your problem here is that you are invoking the JTable(Object[][], Object[]) constructor. If you check out the source code in that link, you can see that it is invoking the JTable(TableModel) constructor internally, having constructed an anonymous instance of AbstractTableModel, which is what is returned by the getModel() method - this can't be cast to a DefaultTableModel.

However: what you are trying to do here won't work anyway. You are saying that the rows of the data are represented by a zero-element array:

Object[][] data = {};

You will not be able to add rows to this, because you can't resize an array once constructed.

Instead of this, you should construct an explicit DefaultTableModel:

TableModel tableModel = new DefaultTableModel(column, rowCount);

and then use this to construct the JTable:

JTable toDoTable = new JTable(tableModel) { ... }

I am not familiar with swing at all, but it looks like DefaultTableModel is backed by a Vector for the row data, so you don't need to know the exact value of rowCount up front.

like image 62
Andy Turner Avatar answered Feb 13 '23 22:02

Andy Turner