Question

I have a JTable called "Cart" where user can add products before buying them. The only editable column in that table is the last column called Quantity, which allows users to change the amount of products they wish to buy. By default when adding products this value is one. When I create invoice with these default values, ORDERS DB table is successfully updated. However if I change the amount in quantity cell by typing it, I get an exception I don't know how to fix. It would appear that integer value I'm trying to get from that column is returned as a String, instead of integer.

Basically I have integer tempStock in which I store quantity of products. I get that value from Model of the table in row "i" and last column "4".

int tempStock = (int)cartModel.getValueAt(i, 4);

When program adds new row in this table the fourht column is by default 1, and when I call that value, I do get integer. However, if I type in that column some other value, then I no longer get int back, but String.

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer

I have found a temporary work around, through checking the type of variable:

/** Check if Quantity field was updated **/
if (cartModel.getValueAt(i, 4).getClass().getName().equals("java.lang.Integer")) {
    tempStock = (int)cartModel.getValueAt(i, 4);
} else {
    tempStock = Integer.parseInt((String)cartModel.getValueAt(i, 4));
}
Was it helpful?

Solution

  1. you have to setColumnClass in the TableModel with value Integer for returning int value in the form int tempStock = (int)cartModel.getValueAt(i, 4);

  2. for real sugestions and help you have to edit your question with SSCCE

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