Reputation: 2043
im developing an application and i'm trying to insert a new row into jtable i've followed this tutorial , the user can add/remove product information(row) through a form.the database & the table should be updated ,the remove function works well but i can't insert new row into the table . Note:- when i close the app & run it again the table is updated and here's my code
public class TableModel extends AbstractTableModel {
Object[] values;
String[] columnNames;
private ArrayList productInfoList;
public TableModel() {
super();
Session session = HibernateUtil.openSession();
Query q = session.createQuery("from Product");
productInfoList = new ArrayList(q.list());
session.close();
}
@Override
public int getRowCount() {
//return dataVec.size();
return productInfoList.size();
}
@Override
public int getColumnCount() {
return 9;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Product product = (Product) productInfoList.get(rowIndex);
values = new Object[]{product.getProdectId(),
product.getProductName(), product.getProductBuyingPrice(),
product.getProductSalesPrice(), product.getCategory(), product.getBrand(),
product.getProductQuantity(), product.getProductMinQuantity(), product.getProductDescription()};
return values[columnIndex];
}
@Override
public String getColumnName(int column)
{
columnNames=new String[]{"id","Product Name","Buy price","Sale price ","Category",
"Brand","Quantatity","Min Quantatity","Description"};
return columnNames[column];
}
public void removeRow(int rowIndex) {
productInfoList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
public void insertRow(int rowIndex,Product everyRow) {
productInfoList.add(rowIndex, everyRow);
fireTableRowsInserted(rowIndex, rowIndex);
}
}
this is the code that i try to insert row with
public void AddRow() {
int position = jTable1.getRowCount() - 1;
System.out.println(position); // test
Product product = new Product();
tablemodel.insertRow(position, product);
}
Please help me as i'm get tired of it :|
Upvotes: 0
Views: 818
Reputation: 324108
Your TableModel
is storing a Product
object in an ArrayList.
So, when you want to add a new row to the model you need to create a new Product
object and add the Product
to the ArrayList.
Also, you don't need to invoke table.repaint(), the insertRow(...) method is invoking the fireTableRowsInserted(...) method which will tell the table to repaint the row.
Upvotes: 2