用Java做一个温度转换器 有摄氏度转华氏度有华氏度转摄氏度还有清空按钮且中文显示
时间: 2023-10-03 17:09:14 浏览: 137
好的,以下是Java实现的温度转换器代码,包含摄氏度转华氏度、华氏度转摄氏度和清空按钮功能,且中文显示:
```
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TemperatureConverter extends JFrame implements ActionListener {
private JTextField celsiusField, fahrenheitField;
private JButton cToFButton, fToCButton, clearButton;
public TemperatureConverter() {
setTitle("温度转换器");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建面板
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 5, 5));
// 添加组件到面板
JLabel celsiusLabel = new JLabel("摄氏度:");
panel.add(celsiusLabel);
celsiusField = new JTextField(10);
panel.add(celsiusField);
JLabel fahrenheitLabel = new JLabel("华氏度:");
panel.add(fahrenheitLabel);
fahrenheitField = new JTextField(10);
panel.add(fahrenheitField);
cToFButton = new JButton("摄氏度转华氏度");
cToFButton.addActionListener(this);
panel.add(cToFButton);
fToCButton = new JButton("华氏度转摄氏度");
fToCButton.addActionListener(this);
panel.add(fToCButton);
clearButton = new JButton("清空");
clearButton.addActionListener(this);
panel.add(clearButton);
// 添加面板到窗口
setContentPane(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == cToFButton) {
String celsiusText = celsiusField.getText().trim();
if (!celsiusText.isEmpty()) {
double celsius = Double.parseDouble(celsiusText);
double fahrenheit = celsius * 1.8 + 32;
fahrenheitField.setText(String.format("%.2f", fahrenheit));
}
} else if (e.getSource() == fToCButton) {
String fahrenheitText = fahrenheitField.getText().trim();
if (!fahrenheitText.isEmpty()) {
double fahrenheit = Double.parseDouble(fahrenheitText);
double celsius = (fahrenheit - 32) / 1.8;
celsiusField.setText(String.format("%.2f", celsius));
}
} else if (e.getSource() == clearButton) {
celsiusField.setText("");
fahrenheitField.setText("");
}
}
public static void main(String[] args) {
// 设置Swing的外观为系统默认
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
new TemperatureConverter();
}
}
```
使用方法:运行程序后,在摄氏度输入框或华氏度输入框中输入一个数值,然后点击“摄氏度转华氏度”或“华氏度转摄氏度”按钮,即可在另一个输入框中得到转换后的结果。点击“清空”按钮可以清空输入框中的内容。
阅读全文