Need help getting this simple Fahrenheit to Celsius application working in java

I need this app to convert the number entered by the user JTextField

to celsius and display it in JLabel

. You seem to be having trouble parsing the data entered in the double? This is one mistake among many. Can anyone help me figure out what happened? (I only entered double values ​​in the textbox when I tested it, and it still won't change it to double.)

public class TempConvertGUI extends JFrame{
    private JLabel result;
    private final JTextField input;

    public TempConvertGUI()
        super("Fahrenheit to Celsius Application");

        setLayout(new FlowLayout());

        //TempConvert convert=new TempConvert();

        input=new JTextField(10);
        input.setToolTipText("Enter degrees in fahrenheit here.");
        input.addActionListener(new ActionListener()
            private double temp;
            private String string;

            public void actionPerformed(ActionEvent event) {
                        string=String.format("%d degrees Celsius", convertToCelsius(temp));


        result=new JLabel();


    private double convertToCelsius(double fahrenheit)
        return (5/9)*(fahrenheit-32);



source to share

3 answers

  • The ActionCommand for the JTextField has never been set, so it will be an empty string. If you want to parse the data in the JTextField, get its value and parse that value (for example temp=Double.parseDouble(input.getText());

  • See API for Format Strings - Use %f

    to parse floating point values
  • No need to add and remove result

    JLabel in ActionPerformed, it is already added to UI - just provide text
  • (5/9)

    - integer math, if you want floating point math, give one of the numbers as the correct data type: (5/9d)



You seem to have this exception

java.util.IllegalFormatConversionException: d != java.lang.Double


And this is because of this line of code

string=String.format("%d degrees Celsius", convertToCelsius(temp));



is an integer; you want to use %f

for double ( convertToCelsius

returns double).

So change it to

string=String.format("%f degrees Celsius", convertToCelsius(temp));




Instead, temp=Double.parseDouble(event.getActionCommand());

you have to parse the input from input.getText()




All Articles