Java中使用JFrame创建登录窗口 建立用户表user,当点击登录按钮时,对输入的用户名为和密码进行验 证: 当输入的用户和密码与user表中某一条记录相匹配时,弹出消息对话框,提示信息为:“用户名和密码正确”,否则,提示信息为:“用户名或密码错误”。 点击重置按钮时: 用户名文本框和密码文本框的内容被清空。
时间: 2024-03-10 09:45:53 浏览: 22
好的,下面是一份使用JFrame创建登录窗口的示例代码,实现了用户登录验证和重置功能:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class LoginWindow extends JFrame implements ActionListener {
private JLabel nameLabel, passwordLabel;
private JTextField nameTextField;
private JPasswordField passwordField;
private JButton loginButton, resetButton;
public LoginWindow() {
setTitle("Login");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建窗口内容
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
nameLabel = new JLabel("Name:");
nameTextField = new JTextField();
panel.add(nameLabel);
panel.add(nameTextField);
passwordLabel = new JLabel("Password:");
passwordField = new JPasswordField();
panel.add(passwordLabel);
panel.add(passwordField);
loginButton = new JButton("Login");
loginButton.addActionListener(this);
panel.add(loginButton);
resetButton = new JButton("Reset");
resetButton.addActionListener(this);
panel.add(resetButton);
add(panel);
setVisible(true);
}
// 处理登录和重置按钮点击事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String name = nameTextField.getText();
String password = new String(passwordField.getPassword());
// 验证用户名和密码
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "password");
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM user WHERE name = '" + name + "' AND password = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
JOptionPane.showMessageDialog(this, "Username and password correct!");
} else {
JOptionPane.showMessageDialog(this, "Username or password incorrect!");
}
conn.close();
} catch (SQLException exc) {
JOptionPane.showMessageDialog(this, "Error: " + exc.getMessage());
}
} else if (e.getSource() == resetButton) {
nameTextField.setText("");
passwordField.setText("");
}
}
public static void main(String[] args) {
new LoginWindow();
}
}
```
这个示例代码创建了一个包含用户名、密码输入框,以及登录和重置按钮的窗口。当点击登录按钮时,会将用户输入的用户名和密码与数据库表`user`中的记录进行匹配,如果匹配成功,则弹出消息框提示“用户名和密码正确”,否则提示“用户名或密码错误”。当点击重置按钮时,会将用户名和密码输入框的内容清空。
需要注意的是,这个示例代码中的数据库连接信息是硬编码在程序中的,并且使用的是不安全的字符串拼接方式构建SQL语句,容易受到SQL注入攻击。在实际开发中,你需要使用安全的方式处理数据库连接和SQL语句,比如使用连接池、PreparedStatement和参数化查询等。