Search code examples
javastringdoublejtextfield

How do I convert a JTextField string to a double?


My program works with birthday's and age's. I have trouble with trying to convert my JTextField strings to doubles. I used the parse method but still received a error. Please Help!

public class MyPaymentFrame extends JFrame implements ActionListener {

    JTextField txtAge;
    JTextField txtDate;

        public MyPaymentFrame()  {
        Container mycnt = getContentPane();
        mycnt.setLayout(new FlowLayout());

        Color c = new Color(56, 100, 20);
        Font F = new Font("Arial", Font.ITALIC, 20);

        mycnt.add(new JLabel("Enter your Age"));
        txtAge = new JTextField(15);
        mycnt.add(txtAmount);


        mycnt.add(new JLabel("Enter birthdate"));
        txtDate = new JTextField(10);
        mycnt.add(txtDate);

    }
        if (e.getActionCommand().equals("Clear")) {
            txtAge.setText("");
            txtDate.setText("");
        }

        if (e.getActionCommand().equals("Calculate")) {
            // Converting String to Double
            double Amount = Double.parseDouble(txtMonth);

        }

    }
    public static void main(String[] args) {

        Theframe myframe = new Theframe();

    }

}

Solution

  • Apparently txtMonth is a JTexfield, but the Double.parseDouble method receives a String. Check the method's javadoc here.

    Try using:

    double Amount = Double.parseDouble(txtMonth.getText());
    

    Also, this method will throw a NumberFormatException if the text can't be converted to double.