Calculate Fahrenheit to Celsius Temperature in Java
Rohan Sakhale 6/16/2012 code-examplejavajava-swing
# Summary
In-order to convert from Fahrenheit to Celsius, we have to apply a simple logic onto Celsius "Deduct 32, then multiply by 5, then divide by 9".
Our code provides a simple GUI, where the user has to enter the temperature in Fahrenheit and after clicking on convert displays the Celsius 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
# 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 F2C extends JPanel{
JTextField tfInputTemp;
JLabel lInputTemp, lAnswer;
JButton bCalc;
JPanel InputTemp, collections;
public F2C() {
tfInputTemp = new JTextField(15);
lInputTemp = new JLabel(\"Enter Temperature in Fahrenheit: \");
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 celsius = (temp - 32 ) * 5 / 9;
lAnswer.setText(\"Answer: \" + celsius + \" C\");
}
}
});
add(collections);
}
}
class F2CMainDemo{
public static void main(String[] args) {
JFrame f2cFrame = new JFrame(\"Celsius to Fahrenheit Demo Program\");
F2C f2c = new F2C();
f2cFrame.add(f2c);
f2cFrame.setSize(400, 150);
f2cFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2cFrame.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
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