-
Notifications
You must be signed in to change notification settings - Fork 246
/
TemperatureConverter.java
73 lines (67 loc) · 2.32 KB
/
TemperatureConverter.java
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
61
62
63
64
65
66
67
68
69
70
71
72
73
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class TemperatureConverter
{
// Declare the GUI Elements
public static JFrame frmMain;
public static JLabel lblCelsius;
public static JTextField textCelsius;
public static JLabel lblFahrenheit;
public static JTextField textFahrenheit;
public static JButton btnCalculateCtoF;
public static JButton btnCalculateFtoC;
public static void main(String[] args)
{
// Set up the frame
frmMain = new JFrame("Temperature Converter by @TokyoEdtech");
frmMain.setSize(150, 200);
frmMain.setLayout(new FlowLayout());
// Create GUI Elements
lblCelsius = new JLabel("Celsius:");
textCelsius = new JTextField(10);
lblFahrenheit = new JLabel("Fahrenheit:");
textFahrenheit = new JTextField(10);
btnCalculateCtoF = new JButton("Convert C to F");
// Add ActionListener
btnCalculateCtoF.addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Convert C to F
String cText = textCelsius.getText();
double c = Double.parseDouble(cText);
double f = (c * 9 / 5) + 32;
textFahrenheit.setText(String.valueOf(f));
}
}
);
btnCalculateFtoC = new JButton("Convert F to C");
// Add ActionListener
btnCalculateFtoC.addActionListener
(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// Convert F to C
String fText = textFahrenheit.getText();
double f = Double.parseDouble(fText);
double c = (f - 32) * 5 / 9;
textCelsius.setText(String.valueOf(c));
}
}
);
// Add the GUI Elements to the frame
frmMain.add(lblCelsius);
frmMain.add(textCelsius);
frmMain.add(lblFahrenheit);
frmMain.add(textFahrenheit);
frmMain.add(btnCalculateCtoF);
frmMain.add(btnCalculateFtoC);
// Make the frame visible
frmMain.setVisible(true);
}
}