利用javaGUI知识编写一个摄氏度和华氏度的转换
时间: 2023-12-06 22:39:31 浏览: 100
好的,下面是一个简单的Java GUI程序,可以将摄氏度转换为华氏度,以及将华氏度转换为摄氏度。代码如下:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TemperatureConverter extends JFrame implements ActionListener {
private JLabel celsiusLabel;
private JLabel fahrenheitLabel;
private JTextField celsiusField;
private JTextField fahrenheitField;
private JButton convertCelsiusToFahrenheitButton;
private JButton convertFahrenheitToCelsiusButton;
public TemperatureConverter() {
super("Temperature Converter");
// Create the components
celsiusLabel = new JLabel("Celsius:");
fahrenheitLabel = new JLabel("Fahrenheit:");
celsiusField = new JTextField(10);
fahrenheitField = new JTextField(10);
convertCelsiusToFahrenheitButton = new JButton("Convert C to F");
convertFahrenheitToCelsiusButton = new JButton("Convert F to C");
// Add action listeners to the buttons
convertCelsiusToFahrenheitButton.addActionListener(this);
convertFahrenheitToCelsiusButton.addActionListener(this);
// Create a panel for the input fields
JPanel inputPanel = new JPanel(new GridLayout(2, 2));
inputPanel.add(celsiusLabel);
inputPanel.add(celsiusField);
inputPanel.add(fahrenheitLabel);
inputPanel.add(fahrenheitField);
// Create a panel for the buttons
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(convertCelsiusToFahrenheitButton);
buttonPanel.add(convertFahrenheitToCelsiusButton);
// Add the panels to the frame
add(inputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
// Set the frame properties
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 120);
setLocationRelativeTo(null); // Center the window
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == convertCelsiusToFahrenheitButton) {
double celsius = Double.parseDouble(celsiusField.getText());
double fahrenheit = celsius * 9 / 5 + 32;
fahrenheitField.setText(String.format("%.2f", fahrenheit));
} else if (e.getSource() == convertFahrenheitToCelsiusButton) {
double fahrenheit = Double.parseDouble(fahrenheitField.getText());
double celsius = (fahrenheit - 32) * 5 / 9;
celsiusField.setText(String.format("%.2f", celsius));
}
}
public static void main(String[] args) {
new TemperatureConverter();
}
}
```
运行程序后,将会看到一个包含两个文本输入框和两个按钮的窗口。在输入框中输入摄氏度或华氏度,然后单击相应的按钮,即可将温度转换为另一种单位并显示在另一个文本输入框中。
阅读全文