![](/img/trans.png)
[英]Hibernate, Dao Objects insert into JTable (AbstractTableModel)
[英]insert Row into jtable using AbstractTableModel with hibernate
我正在開發一個應用程序,我正在嘗試向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
對象存儲在ArrayList中。
因此,當您想向模型添加新行時,需要創建一個new Product
對象並將Product
添加到ArrayList。
另外,您不需要調用table.repaint(),insertRow(...)方法將調用fireTableRowsInserted(...)方法,該方法將告訴表重新繪制該行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.