0

trying to return a specific cell. the user selects a row and the value is converted to double. the column is always number 3. this is what I have tried doing so far but i get an error saying cannot convert object to double

        numberRow = TOrders.getSelectedRow();
        TOrders.getSelectedRow();
        subCost = TOrders.getModel().getValueAt(numberRow, 3);

help required !!!

Scooter
  • 6,802
  • 8
  • 41
  • 64
badman123
  • 51
  • 7

2 Answers2

0

You are retrieving an Object instead of a double. You'll need to cast it to a Double in order to be able to treat it as such:

subCost = (Double) TOrders.getModel().getValueAt(numberRow, 3);

Also,

TOrders.getSelectedRow();

does not do anything useful. You should remove this line.

Community
  • 1
  • 1
pietv8x
  • 248
  • 1
  • 9
  • Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double , im now getting this error – badman123 Nov 30 '14 at 22:13
  • Then the value you are trying to retrieve is not a numeric value. Are you using , or . as separator for real numbers? Using , will indeed yield an exception, using . is fine. – pietv8x Nov 30 '14 at 22:19
0

The getValueAt() method of the TableModel interface returns a descendant of Object. Your error message indicates it is a String. So it seems that you should convert the Object reference returned to a String reference with a cast. Then convert that String to a double with Double.parseDouble(). parseDouble will throw a NumberFormatException if the string is not a valid double:

try {
    numberRow = TOrders.getSelectedRow();
    String temp = (String) TOrders.getModel().getValueAt(numberRow, 3);
    subCost = Double.parseDouble(temp);
}
catch (NumberFormatException e)
{
    JOptionPane.showMessageDialog(null, "Item in table was not a valid double - "
             + e.getMessage() );
}

If you want to deal with currency data, you may want to put it in a BigDecimal. Constructing a BigDecimal with a String that does not contain a valid decimal number throws a NumberFormatException.

try {
    numberRow = TOrders.getSelectedRow();
    String temp = (String) TOrders.getModel().getValueAt(numberRow, 3);
    subCost = new BigDecimal(temp);
}
catch (NumberFormatException e)
{
    JOptionPane.showMessageDialog(null, 
         "Item in table was not a valid decimal number");
}
Scooter
  • 6,802
  • 8
  • 41
  • 64