使用hibernate的AbstractTableModel将行插入jtable中



我正在开发一个应用程序,我试图插入一个新的行到jtable我遵循了本教程,用户可以通过表单添加/删除产品信息(行)。数据库& &;表应该更新,删除功能工作得很好,但我不能插入新行到表中。注意:-当我关闭应用程序&再次运行它,表就更新了这是我的代码

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);
}
  }

这是我尝试用

插入行的代码
public void AddRow() {
    int position = jTable1.getRowCount() - 1;
    System.out.println(position); // test
    Product product = new Product();
    tablemodel.insertRow(position, product);
}

请帮帮我,我烦透了:|

您的TableModel在数组列表中存储Product对象。

所以,当你想添加一个新的行到模型中,你需要创建一个new Product对象,并将Product添加到ArrayList。

同样,您不需要调用table.repaint(), insertRow(…)方法正在调用fireTableRowsInserted(…)方法,该方法将告诉表重新绘制行

最新更新