Vanoshan Ramdhani
Vanoshan Ramdhani

Reputation: 63

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)

Upvotes: 0

Views: 7940

Answers (2)

Demonic218
Demonic218

Reputation: 923

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));

Upvotes: 2

Shiksha Verma
Shiksha Verma

Reputation: 130

Try to print the txtTot.getText () to the console and check whether it is in proper decimal format. Incorrect format could be the cause of error.

Upvotes: -1

Related Questions