请给代码加上相应的中文注释
时间: 2024-03-10 12:50:52 浏览: 143
代码 辅助 注释
好的,以下是加上中文注释的代码:
```java
import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login extends JFrame implements ActionListener {
private JLabel titleLabel, usernameLabel, passwordLabel;
private JTextField usernameField;
private JPasswordField passwordField;
private JButton loginButton, registerButton;
public Login() {
super("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 10, 10));
setResizable(false);
// 标题
titleLabel = new JLabel("游戏登录", SwingConstants.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
add(titleLabel);
// 用户名
usernameLabel = new JLabel("用户名:", SwingConstants.RIGHT);
add(usernameLabel);
usernameField = new JTextField(20);
add(usernameField);
// 密码
passwordLabel = new JLabel("密码:", SwingConstants.RIGHT);
add(passwordLabel);
passwordField = new JPasswordField(20);
add(passwordField);
// 登录按钮
loginButton = new JButton("登录");
loginButton.addActionListener(this);
add(loginButton);
// 注册按钮
registerButton = new JButton("注册");
registerButton.addActionListener(this);
add(registerButton);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (action.equals("登录")) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
String url = "jdbc:mysql://localhost:3306/game"; // 数据库连接字符串
String user = "root"; // 数据库用户名
String pass = "123456"; // 数据库密码
try {
// 连接数据库
Connection conn = DriverManager.getConnection(url, user, pass);
Statement stmt = conn.createStatement();
// 查询用户信息是否正确
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username='" + username + "' AND password='" + password + "'");
if (rs.next()) {
JOptionPane.showMessageDialog(this, "登录成功!");
} else {
JOptionPane.showMessageDialog(this, "用户名或密码不正确!");
}
stmt.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
} else if (action.equals("注册")) {
// 实现注册逻辑
}
}
public static void main(String[] args) {
new Login();
}
}
```
希望这份代码能对您有所帮助。
阅读全文