Java设置一个简单的页面第一个按钮华氏度转摄氏度 第二个按钮摄氏度转华氏度第三个按钮清除 同时使用JDBC访问数据源代码实现
时间: 2023-08-03 09:06:14 浏览: 76
以下是一个简单的Java页面,包含三个按钮:一个用于将华氏度转换为摄氏度,一个用于将摄氏度转换为华氏度,以及一个用于清除输入字段的按钮。此外,代码还包括使用JDBC访问数据源的实现。
```java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class TemperatureConverter extends Frame implements ActionListener {
// GUI components
private TextField fahrenheitField;
private TextField celsiusField;
private Button toCelsiusButton;
private Button toFahrenheitButton;
private Button clearButton;
// Database connection
private Connection conn;
public TemperatureConverter() {
// Initialize GUI components
fahrenheitField = new TextField(10);
celsiusField = new TextField(10);
toCelsiusButton = new Button("Fahrenheit to Celsius");
toFahrenheitButton = new Button("Celsius to Fahrenheit");
clearButton = new Button("Clear");
// Add event listeners to buttons
toCelsiusButton.addActionListener(this);
toFahrenheitButton.addActionListener(this);
clearButton.addActionListener(this);
// Add components to frame
setLayout(new FlowLayout());
add(new Label("Fahrenheit:"));
add(fahrenheitField);
add(new Label("Celsius:"));
add(celsiusField);
add(toCelsiusButton);
add(toFahrenheitButton);
add(clearButton);
// Initialize database connection
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
} catch (Exception e) {
e.printStackTrace();
}
// Set frame properties
setTitle("Temperature Converter");
setSize(300, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == toCelsiusButton) {
// Convert Fahrenheit to Celsius
try {
double fahrenheit = Double.parseDouble(fahrenheitField.getText());
double celsius = (fahrenheit - 32) * 5 / 9;
celsiusField.setText(Double.toString(celsius));
// Save conversion to database
PreparedStatement stmt = conn.prepareStatement("INSERT INTO conversions (fahrenheit, celsius) VALUES (?, ?)");
stmt.setDouble(1, fahrenheit);
stmt.setDouble(2, celsius);
stmt.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (e.getSource() == toFahrenheitButton) {
// Convert Celsius to Fahrenheit
try {
double celsius = Double.parseDouble(celsiusField.getText());
double fahrenheit = celsius * 9 / 5 + 32;
fahrenheitField.setText(Double.toString(fahrenheit));
// Save conversion to database
PreparedStatement stmt = conn.prepareStatement("INSERT INTO conversions (celsius, fahrenheit) VALUES (?, ?)");
stmt.setDouble(1, celsius);
stmt.setDouble(2, fahrenheit);
stmt.executeUpdate();
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (e.getSource() == clearButton) {
// Clear input fields
fahrenheitField.setText("");
celsiusField.setText("");
}
}
public static void main(String[] args) {
new TemperatureConverter();
}
}
```
请注意,此代码仅用于演示目的,需要根据实际情况进行修改和优化。
阅读全文