用JAVA做一个温度转换的表格,有摄氏度转华氏度有华氏度转摄氏度,有清除
时间: 2024-02-07 18:02:49 浏览: 56
好的,以下是一个简单的用 Java 实现的温度转换表格:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TemperatureConverter extends JFrame {
private JTextField celsiusField, fahrenheitField;
public TemperatureConverter() {
super("Temperature Converter");
// 设置窗口大小和位置
setSize(300, 150);
setLocationRelativeTo(null);
// 创建输入框和标签
celsiusField = new JTextField(10);
fahrenheitField = new JTextField(10);
JLabel celsiusLabel = new JLabel("Celsius");
JLabel fahrenheitLabel = new JLabel("Fahrenheit");
// 创建按钮
JButton celsiusToFahrenheitButton = new JButton("Convert >>");
JButton fahrenheitToCelsiusButton = new JButton("<< Convert");
JButton clearButton = new JButton("Clear");
// 添加事件监听器
celsiusToFahrenheitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String celsiusText = celsiusField.getText();
if (!celsiusText.isEmpty()) {
double celsius = Double.parseDouble(celsiusText);
double fahrenheit = celsius * 9 / 5 + 32;
fahrenheitField.setText(String.format("%.2f", fahrenheit));
}
}
});
fahrenheitToCelsiusButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String fahrenheitText = fahrenheitField.getText();
if (!fahrenheitText.isEmpty()) {
double fahrenheit = Double.parseDouble(fahrenheitText);
double celsius = (fahrenheit - 32) * 5 / 9;
celsiusField.setText(String.format("%.2f", celsius));
}
}
});
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
celsiusField.setText("");
fahrenheitField.setText("");
}
});
// 创建布局
JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
inputPanel.add(celsiusField);
inputPanel.add(celsiusLabel);
inputPanel.add(fahrenheitField);
inputPanel.add(fahrenheitLabel);
JPanel buttonPanel = new JPanel(new GridLayout(1, 3, 5, 5));
buttonPanel.add(celsiusToFahrenheitButton);
buttonPanel.add(fahrenheitToCelsiusButton);
buttonPanel.add(clearButton);
// 将布局添加到窗口中
setLayout(new BorderLayout());
add(inputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
TemperatureConverter converter = new TemperatureConverter();
converter.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
converter.setVisible(true);
}
}
```
这个程序使用了 Java 的图形用户界面 Swing,可以在窗口中输入摄氏度或华氏度,然后点击转换按钮进行温度转换。点击清除按钮可以清除输入框中的内容。
阅读全文