- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaTemperatureConverter.java
More file actions
Latest commit
94 lines (71 loc) · 2.85 KB
/
Copy pathJavaTemperatureConverter.java
File metadata and controls
94 lines (71 loc) · 2.85 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
importjavax.swing.*;
importjava.awt.event.*;
publicclassJavaTemperatureConverter {
publicstaticvoidmain(String[] args) {
JFrameframe = newJFrame("Temperature Converter");
frame.setSize(400, 300);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Labels
JLabelcLabel = newJLabel("Celsius:");
cLabel.setBounds(30, 30, 100, 30);
JLabelfLabel = newJLabel("Fahrenheit:");
fLabel.setBounds(30, 80, 100, 30);
// Text Fields
JTextFieldcText = newJTextField();
cText.setBounds(130, 30, 150, 30);
JTextFieldfText = newJTextField();
fText.setBounds(130, 80, 150, 30);
// Buttons
JButtonconvertBtn = newJButton("Convert");
convertBtn.setBounds(30, 140, 100, 30);
JButtonclearBtn = newJButton("Clear");
clearBtn.setBounds(140, 140, 100, 30);
JButtonexitBtn = newJButton("Exit");
exitBtn.setBounds(250, 140, 100, 30);
// ================= EVENT HANDLING =================
// Convert Button
convertBtn.addActionListener(newActionListener() {
publicvoidactionPerformed(ActionEvente) {
try {
// If Celsius field is not empty → convert to Fahrenheit
if (!cText.getText().isEmpty()) {
doublec = Double.parseDouble(cText.getText());
doublef = (c * 9 / 5) + 32;
fText.setText(String.valueOf(f));
}
// If Fahrenheit field is not empty → convert to Celsius
elseif (!fText.getText().isEmpty()) {
doublef = Double.parseDouble(fText.getText());
doublec = (f - 32) * 5 / 9;
cText.setText(String.valueOf(c));
}
} catch (Exceptionex) {
JOptionPane.showMessageDialog(frame, "Invalid Input");
}
}
});
// Clear Button
clearBtn.addActionListener(newActionListener() {
publicvoidactionPerformed(ActionEvente) {
cText.setText("");
fText.setText("");
}
});
// Exit Button
exitBtn.addActionListener(newActionListener() {
publicvoidactionPerformed(ActionEvente) {
frame.dispose(); // closes window
}
});
// Add to Frame
frame.add(cLabel);
frame.add(fLabel);
frame.add(cText);
frame.add(fText);
frame.add(convertBtn);
frame.add(clearBtn);
frame.add(exitBtn);
frame.setVisible(true);
}
}