gui界面修改密码java
时间: 2023-07-02 18:23:24 浏览: 134
你可以使用Java Swing库来创建一个GUI界面,然后使用Java的JDBC API来连接数据库并更新密码。以下是一个简单的示例代码:
```java
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class PasswordChangeGUI extends JFrame implements ActionListener {
private JLabel lblUsername, lblOldPassword, lblNewPassword;
private JTextField txtUsername;
private JPasswordField txtOldPassword, txtNewPassword;
private JButton btnUpdate;
public PasswordChangeGUI() {
setTitle("Password Change");
setSize(350, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4, 2));
lblUsername = new JLabel("Username:");
txtUsername = new JTextField(20);
panel.add(lblUsername);
panel.add(txtUsername);
lblOldPassword = new JLabel("Old Password:");
txtOldPassword = new JPasswordField(20);
panel.add(lblOldPassword);
panel.add(txtOldPassword);
lblNewPassword = new JLabel("New Password:");
txtNewPassword = new JPasswordField(20);
panel.add(lblNewPassword);
panel.add(txtNewPassword);
btnUpdate = new JButton("Update Password");
btnUpdate.addActionListener(this);
panel.add(btnUpdate);
add(panel);
}
public void actionPerformed(ActionEvent e) {
String username = txtUsername.getText();
String oldPassword = new String(txtOldPassword.getPassword());
String newPassword = new String(txtNewPassword.getPassword());
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE username=? AND password=?");
ps.setString(1, username);
ps.setString(2, oldPassword);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
ps = con.prepareStatement("UPDATE users SET password=? WHERE username=?");
ps.setString(1, newPassword);
ps.setString(2, username);
int rowsUpdated = ps.executeUpdate();
if (rowsUpdated > 0) {
JOptionPane.showMessageDialog(this, "Password updated successfully");
} else {
JOptionPane.showMessageDialog(this, "Failed to update password");
}
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password");
}
con.close();
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "Error updating password: " + ex.getMessage());
}
}
public static void main(String[] args) {
PasswordChangeGUI gui = new PasswordChangeGUI();
gui.setVisible(true);
}
}
```
在这个例子中,我们使用了JDBC API来连接MySQL数据库。你需要将以下代码中的数据库连接信息替换成你自己的:
```java
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
```
这里的mydatabase是数据库名称,root是用户名,password是密码。你需要根据你自己的设置来修改这些参数。
阅读全文