0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.