Home > database >  Fill JTable with data from database
Fill JTable with data from database

Time:06-02

I need to create JTable with data loaded from database, but I am struggling with converting ArrayList to something, that supports table model.

I need to store data like this:

  loadProducts();
    data = new Object[][]{
            {1, "Big Mac", 100, 1},
            {2, "McChicken", 40, 1},
            {3, "Cheese", 100, 1}

    };

And than I use this function for creating table, but I get only last element from my database. How can I store every row from database here?

ArrayList<Produkt> productList;

private void createTable() {


    String col[] = {"ID", "name", "price", "category"};
    Object[][] data = new Object[0][];

    DefaultTableModel tableModel = new DefaultTableModel(col, 0);
    productTable.setModel(tableModel);

    for (int i = 0; i < productList.size(); i  ) {
        int id = productList.get(i).getId();
        String  name = productList.get(i).getName();
        double price = productList.get(i).getPrice();
        int category = prodcttList.get(i).getCategory();

        data = new Object[][]{
                {id, name, price, category}
        };

    }
    productsTable.setModel(new DefaultTableModel(
            data, col));
}

CodePudding user response:

At every iteration, you're creating a new matrix data with only the info of the last product iterated. This is why you're seeing only the last item. This is just a syntax problem.

Assuming the productList already contains the results from your database, you could initialize the rows of your matrix data with the number of products in your list, while the number of columns with the fixed value 4, which is the number of fields you want to display (id, name, price and category).

ArrayList<Produkt> productList;

private void createTable() {
    String col[] = {"ID", "name", "price", "category"};
    
    //Initialize the number of rows of your matrix with the number of products in your list
    Object[][] data = new Object[productList.size()][4];

    //Copy every i-th product field in its corresponding column
    for (int i = 0; i < productList.size(); i  ) {
        data[i][0] = productList.get(i).getId();
        data[i][1] = productList.get(i).getName();
        data[i][2] = productList.get(i).getPrice();
        data[i][3] = productList.get(i).getCategory();
    }
    
    productTable.setModel(new DefaultTableModel(data, col));
}
  • Related