Calculate Celsius to Fahrenheit Temperature in Java

6/16/2012 code-examplejavajava-swing

# Summary

In-order to convert from Celsius to Fahrenheit, we have to apply a simple logic onto Celsius "Multiply by 9, then divide by 5, then add 32".

Our code provides a simple GUI, where the user has to enter the temperature in Celsius and after clicking on convert displays the Fahrenheit temperature below button in the form of JLabel. The Class has been designed by extending JPanel which can be called from other classes and added onto the JFrame for displaying.

# Screenshot

Calculate Celsius to Fahrenheit Temperature in Java Screenshot

# Code

package com.rohansakhale.treedemo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 *
 * @author RohanSakhale
 */
public class C2F extends JPanel {
    
    JTextField tfInputTemp;
    JLabel lInputTemp, lAnswer;
    JButton bCalc;
    JPanel InputTemp, collections;
    
    public C2F() {
        tfInputTemp = new JTextField(15);
        lInputTemp = new JLabel("Enter Temperature in Celsius: ");
        lAnswer = new JLabel("Answer: ");
        bCalc = new JButton("Convert");
        InputTemp = new JPanel();
        collections = new JPanel();
        collections.setLayout(new BoxLayout(collections, BoxLayout.Y_AXIS));
        InputTemp.add(lInputTemp);
        InputTemp.add(tfInputTemp);
        collections.add(InputTemp);
        collections.add(bCalc);
        collections.add(lAnswer);
        bCalc.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!tfInputTemp.getText().equals("")) {
                    double temp = Double.parseDouble(tfInputTemp.getText());
                    double fahrenheit = ((temp * 9) / 5) + 32;
                    lAnswer.setText("Answer: " + fahrenheit + " F");
                }
            }
        });
        add(collections);
    }
}

class C2FMainDemo{
    public static void main(String[] args) {
        JFrame c2fFrame = new JFrame("Celsius to Fahrenheit Demo Program");
        C2F c2f = new C2F();
        c2fFrame.add(c2f);
        c2fFrame.setSize(400, 150);
        c2fFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        c2fFrame.setVisible(true);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60