用javaSwing和mysql数据库做的一个登录页面,并且加入一个重置按钮
时间: 2024-02-13 20:07:04 浏览: 22
好的,关于你的问题,我可以提供以下步骤供参考:
1. 首先需要在 Java Swing 中创建一个登录页面,包括用户名、密码的输入框和一个登录按钮以及一个重置按钮。可以使用 JTextField 和 JPasswordField 来创建输入框,使用 JButton 来创建按钮。例如:
```
JFrame frame = new JFrame("登录");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
JLabel userLabel = new JLabel("用户名:");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("密码:");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
JButton loginButton = new JButton("登录");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
JButton resetButton = new JButton("重置");
resetButton.setBounds(100, 80, 80, 25);
panel.add(resetButton);
frame.setVisible(true);
```
2. 然后需要编写连接 MySQL 数据库的代码,在登录按钮的事件监听中,判断用户名和密码是否正确。如果正确,则登录成功,否则弹出错误提示框。例如:
```
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
String username = userText.getText();
String password = new String(passwordText.getPassword());
PreparedStatement ps = conn.prepareStatement("SELECT * FROM user WHERE username = ? AND password = ?");
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, "登录成功");
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误");
}
rs.close();
ps.close();
conn.close();
```
3. 最后在重置按钮的事件监听中,清空用户名和密码的输入框。例如:
```
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userText.setText("");
passwordText.setText("");
}
});
```
这样,当用户点击重置按钮时,用户名和密码的输入框就会被清空。当然,具体实现还需要根据你的具体应用场景进行调整。希望这个回答能够帮到你!