Search code examples
javastringdoublejtextfieldjcombobox

Convert String to Double - JAVA


private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:

        //9


        txtTot.setText(jComboBox1.getSelectedItem().toString());
        tot= Double.parseDouble(txtTot.getText());
        CMB= (Double)jComboBox1.getSelectedItem();
        Total2=tot+CMB;
        txtTot.setText(Double.toString(Total2));

    }   

From the ComboBox I'm setting the jtextfield and the second line I'm taking the string from the textfield and trying to convert it into a double.

Error below:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at test.Test.jComboBox1ActionPerformed(Test.java:392)
    at test.Test.access$600(Test.java:18)
    at test.Test$7.actionPerformed(Test.java:134)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1258)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:586)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622)

Solution

  • To me it seems like you are selecting a value from a combobox then trying to add them together to create a grand total, with the total being updated every time you select a new value from the combobox.

    This seems to be working for me, Note I've taken the first line away because it interfered with the existing total.

    tot= Double.parseDouble(txtTot.getText());
    CMB = Double.parseDouble((String) jComboBox1.getSelectedItem());
    Total2=tot+CMB;
    txtTot.setText(Double.toString(Total2));