Question

I've got these two forms: 'Fashion and footwear' and 'Shopping Cart' in NetBeans. The first form contains 4 buttons. The other contains two tables CurrentPurchases and PreviousPurchases. When any button is clicked from the first form, the item name and price is transferred to the CurrentPurchases table in the other form. What code/query should I use to acheive this? I tried this code but it didn't work.

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{}

This line shows error:

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

Note: CurrentPurchases table is in the other form, not this form.

Was it helpful?

Solution

Your problem in next. You create new DefaultTableModel and add new row to that, but it's local object and it isn't used later:

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

You need to get model from your table, to which you want to add a new row. For example you have 2 methods for creation table and for adding row to that table:

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

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

here targetTable it is your table(CurrentPurchases). You need to have reference to that.

Read tutorial for JTable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top