Java错误:javax.swing.JTable $ 1无法强制转换为javax.swing.table.DefaultTableModel

时间:2015-12-09 08:35:21

标签: java jtable

我尝试做的是在JTableJPanel的新实例中创建JFrame,我在添加行时遇到错误表:

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

    }

中的添加行发生错误

2 个答案:

答案 0 :(得分:5)

您的问题是您正在调用JTable(Object[][], Object[])构造函数。如果您查看该链接中的源代码,您可以看到它在内部调用JTable(TableModel)构造函数,构建了一个AbstractTableModel的匿名实例,这是getModel()返回的内容}方法 - 这不能转换为DefaultTableModel

然而:无论如何,你在这里尝试做什么都行不通。你是说数据的行由零元素数组表示:

Object[][] data = {};

您将无法向其中添加行,因为一旦构造完就无法调整数组大小。

而不是这个,你应该构建一个明确的DefaultTableModel

TableModel tableModel = new DefaultTableModel(column, rowCount);

然后使用它来构造JTable

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

我根本不熟悉swing,但看起来DefaultTableModel支持Vector行数据,所以你不需要知道{{1}的确切值在前面。

答案 1 :(得分:0)

考虑这个稍微改变的代码:

    //Create the new model for the table
    DefaultTableModel model = new DefaultTableModel();

    ConnectMSSQLServer connServer = new ConnectMSSQLServer();
    //Try with catch for auto-closing result set
    try(ResultSet rs = connServer.dbConnect()) {
        while (rs.next()) {
            String id = rs.getString("id");
            String title = rs.getString("title");
            model.addRow(new Object[] { id, title });
        }
    } catch (Exception e) {
        //HANDLE THIS!
    }
    //Now populate the table with the new model
    toDoTable.setModel(model);