0

I am new to Java so please bare with me :).

I created a function that fetch the records from the table.

public ArrayList<Object> getAll() {
    try {
        ArrayList<Object> resultList = new ArrayList<>();
        query = this.conn.prepareStatement("select * from " +
                this.currentTable + this.tableClass.getWhere());
        ResultSet result = query.executeQuery();
        ResultSetMetaData meta = result.getMetaData();
        int totalColumn = meta.getColumnCount();
        while(result.next()) {
            ArrayList<Object> obj = new ArrayList<>();
            for (int x = 1; x < totalColumn; x++) {
                obj.add(result.getObject(x));
            }
            resultList.add(obj);
        }
        result.close();
        query.close();
        return resultList;
    } catch (Exception e) {
        System.out.println("Error : " + e.getMessage());
    }
    return null;
}

Now, I want to display the ArrayList above in my JTable.

 DefaultTableModel model = new DefaultTableModel();
 
 ArrayList<Object> obj = this.getAll(); //call the method above

 // How to insert the records above.

 tableResult.setModel(model);

The problem is, there is an error while inserting an ArrayList in a JTable. I tried to cast ArrayList to Object[] but it has also an error.

Does anybody know?

smzapp
  • 809
  • 1
  • 12
  • 33
  • You have two choices. You can create your own class that implements interface [javax.swing.table.TableModel](https://docs.oracle.com/javase/8/docs/api/javax/swing/table/TableModel.html). When I write an implementation of that interface, I always write a class that extends `AbstractTableModel`. Or you can extend `DefaultTableModel` but then you need to cast your `ArrayList` either to a two-dimensional array, i.e. `Object[][]` or a [java.util.Vector](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html) where every element in the `Vector` is itself another `Vector`. – Abra Jun 05 '21 at 05:15
  • @Abra I tried to cast to `Object[]` but there is an error in casting ArrayList to Object. How did you do it? `java.util.ArrayList cannot be cast to [[Ljava.lang.Object` – smzapp Jun 05 '21 at 05:21
  • I said **two** dimensional array. `Object[]` is a ___one___ dimensional array. That's why you are getting cast exception. Does this help? https://stackoverflow.com/questions/10620448/most-simple-code-to-populate-jtable-from-resultset Or just Google for ___database query result to tablemodel___ – Abra Jun 05 '21 at 05:23
  • 1) Get rid of the ArrayList, there is no need for it. 2) Just use the DefaultTableModel. Instead of add a row of data to the ArrayList you use the `addRow(...)` method of the `DefaultTableModel` to add the data to the model. See: https://stackoverflow.com/questions/55627828/how-to-get-a-defaulttablemodel-objects-data-into-a-subclass-of-defaulttablemode/55635012#55635012 a basic example of this approach. – camickr Jun 05 '21 at 15:31

0 Answers0