gpt4 book ai didi

java - 从 netbeans 中的另一种形式添加表中的行

转载 作者:行者123 更新时间:2023-12-01 13:50:31 24 4
gpt4 key购买 nike

我在 NetBeans 中有这两种形式:“时装和鞋类”和“购物车”。第一个表单包含 4 个按钮。另一个包含两个表 CurrentPurchases 和 PreviousPurchases。当从第一个表单中单击任何按钮时,商品名称和价格将传输到另一个表单中的 CurrentPurchases 表中。我应该使用什么代码/查询来实现此目的?我尝试了这段代码,但没有成功。

int dress1=100;
DefaultTableModel CurrPurchases=(DefaultTableModel)CurrentPurchases.getModel();
double price1=Double.parseDouble(Price1.getText());
int rows=CurrPurchases.getRowCount();
if(rows > 0){
for (int i = 0; i < rows; i++) {
CurrPurchases.removeRow(0);
}
}
try{
Connection connection=getConnection();
ResultSet curprs=null;
Statement buy1stmt=connection.createStatement();
String Buy1Query1="Update Products set Quantity=Quantity-1 where Product_no=1;";
String Buy1Query2="Insert into Buy values('"+Pname1.getText()+"',"+price1+");";
buy1stmt.executeUpdate(Buy1Query1);
buy1stmt.executeUpdate(Buy1Query2);
dress1--;
if(dress1==0){
JOptionPane.showMessageDialog(null,"Sorry, This Item is Out of Stock!");
}
new ShoppingCart().setVisible(true);
PreparedStatement buy2stmt=connection.prepareStatement("Select * from Buy;");
curprs=buy2stmt.executeQuery();
if(curprs.last()){
CurrPurchases.addRow(new Object[]{curprs.getString(1),curprs.getDouble(2)});
}
}
catch(Exception ex){
ex.printStackTrace();
}
finally{}

此行显示错误:

DefaultTableModel CurrPurchases=(DefaultTableModel)CurrentPurchases.getModel();

注意:CurrentPurchases 表是其他表单,而不是此表单。

最佳答案

接下来是你的问题。您创建新的 DefaultTableModel 并向其中添加新行,但它是本地对象,以后不会使用:

DefaultTableModel CurrentPurchases= new DefaultTableModel();
Pname=rs.getString("ProductName");
Price=rs.getString("Price");
CurrentPurchases.addRow(new Object[]{Pname,Price});

您需要从表中获取要向其中添加新行的模型。例如,您有两种创建表和向该表添加行的方法:

    public void init() {
targetTable = new JTable(new DefaultTableModel());
}

public void addRow(){
((DefaultTableModel)targetTable.getModel()).addRow(new Object[]{});
}

此处targetTable是您的表格(CurrentPurchases)。您需要引用一下。

阅读tutorial for JTable .

关于java - 从 netbeans 中的另一种形式添加表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19996678/

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