Adding data to a JTable from a database

26 views Asked by At

I've created a class 'ProductTable' which is extends to JTable. The purpose of the class is to load data from a database and add all the data to the table when it is instantiating. Below is what I tried.

public class ProductTable extends JTable {

    static Statement st;
    static Connection conn;
    static ResultSet rs;

    public ProductTable() {
        
        try {
            conn = ConnectDB.connect();
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
               loadProductTable();
        } catch (SQLException ex) {
               Logger.getLogger(ProductTable.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void loadProductTable() throws SQLException {
            
        String sql = "SELECT product_id, produce_code, product_name, category_id, unit_in_stock, unit_price FROM tblproduct";
        st = conn.prepareStatement(sql);
        rs = st.executeQuery(sql);
        while (rs.next()) {
            Object id = String.valueOf(rs.getInt("product_id"));
            Object code = String.valueOf(rs.getLong("produce_code"));
            Object name = rs.getString("product_name");
            Object category = String.valueOf(rs.getInt("category_id"));
            Object instock = String.valueOf(rs.getFloat("unit_in_stock"));
            Object price = String.valueOf((long) rs.getFloat("unit_price"));
            
            
            Object[] objects = new Object[] {id,code,name,category,instock,price};
            
            setModel(new javax.swing.table.DefaultTableModel(
                    new Object [][] {    
                        objects                        
                    },
                    new String [] {
                        "ID", "CODE", "NAME", "CATEGORY", "IN STOCK", "UNIT PRICE", ""
                    }            
            ));
                
            
        }
    }
}

The problem is when I ran the program from another class, the table only shows the last row of data.

I tried to add the method addRow() at the end of setModel(........).addRow(); but Netbeans says "void type not allowed here".

0

There are 0 answers