gpt4 book ai didi

java - 使用带有 hibernate 的 AbstractTableModel 将 Row 插入 jtable

转载 作者:行者123 更新时间:2023-12-02 05:37:23 25 4
gpt4 key购买 nike

我正在开发一个应用程序,我正在尝试将新行插入到 jtable 中我关注了this tutorial ,用户可以通过表单添加/删除产品信息(行)。数据库和表应该更新,删除功能运行良好,但我无法将新行插入表中。注意:-当我关闭应用程序并再次运行它时,表格会更新这是我的代码

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 中。

因此,当您想要向模型添加新行时,您需要创建一个新 Product 对象并将 Product 添加到 ArrayList。

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

关于java - 使用带有 hibernate 的 AbstractTableModel 将 Row 插入 jtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com