-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaTemperatureConverter.java
More file actions
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
import javax.swing.*;
import java.awt.event.*;
public class JavaTemperatureConverter {
public static void main(String[] args) {
JFrame frame = new JFrame("Temperature Converter");
frame.setSize(400, 300);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Labels
JLabel cLabel = new JLabel("Celsius:");
cLabel.setBounds(30, 30, 100, 30);
JLabel fLabel = new JLabel("Fahrenheit:");
fLabel.setBounds(30, 80, 100, 30);
// Text Fields
JTextField cText = new JTextField();
cText.setBounds(130, 30, 150, 30);
JTextField fText = new JTextField();
fText.setBounds(130, 80, 150, 30);
// Buttons
JButton convertBtn = new JButton("Convert");
convertBtn.setBounds(30, 140, 100, 30);
JButton clearBtn = new JButton("Clear");
clearBtn.setBounds(140, 140, 100, 30);
JButton exitBtn = new JButton("Exit");
exitBtn.setBounds(250, 140, 100, 30);
// ================= EVENT HANDLING =================
// Convert Button
convertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// If Celsius field is not empty → convert to Fahrenheit
if (!cText.getText().isEmpty()) {
double c = Double.parseDouble(cText.getText());
double f = (c * 9 / 5) + 32;
fText.setText(String.valueOf(f));
}
// If Fahrenheit field is not empty → convert to Celsius
else if (!fText.getText().isEmpty()) {
double f = Double.parseDouble(fText.getText());
double c = (f - 32) * 5 / 9;
cText.setText(String.valueOf(c));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Invalid Input");
}
}
});
// Clear Button
clearBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cText.setText("");
fText.setText("");
}
});
// Exit Button
exitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
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);
}
}