javaswing实现注册登录代码
时间: 2023-09-13 14:10:46 浏览: 42
以下是一个简单的 Java Swing 实现注册登录的代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginDemo extends JFrame implements ActionListener {
// 登录界面的组件
JLabel userLabel = new JLabel("用户名:");
JTextField userText = new JTextField();
JLabel passLabel = new JLabel("密码:");
JPasswordField passText = new JPasswordField();
JButton loginButton = new JButton("登录");
JButton registerButton = new JButton("注册");
// 注册界面的组件
JLabel newUserLabel = new JLabel("新用户名:");
JTextField newUserText = new JTextField();
JLabel newPassLabel = new JLabel("新密码:");
JPasswordField newPassText = new JPasswordField();
JButton confirmButton = new JButton("确认");
JButton cancelButton = new JButton("取消");
// 构造函数
public LoginDemo() {
// 设置登录界面的组件
setTitle("登录");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
add(userLabel);
add(userText);
add(passLabel);
add(passText);
add(loginButton);
add(registerButton);
loginButton.addActionListener(this);
registerButton.addActionListener(this);
// 设置注册界面的组件
setTitle("注册");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
add(newUserLabel);
add(newUserText);
add(newPassLabel);
add(newPassText);
add(confirmButton);
add(cancelButton);
confirmButton.addActionListener(this);
cancelButton.addActionListener(this);
}
// 监听事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
// 登录按钮被点击
String user = userText.getText();
String pass = new String(passText.getPassword());
// 判断用户名和密码是否正确
if (user.equals("admin") && pass.equals("123456")) {
JOptionPane.showMessageDialog(null, "登录成功!");
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误!");
}
} else if (e.getSource() == registerButton) {
// 注册按钮被点击
setContentPane(getContentPane());
setTitle("注册");
setVisible(true);
} else if (e.getSource() == confirmButton) {
// 确认按钮被点击
String newUser = newUserText.getText();
String newPass = new String(newPassText.getPassword());
// 注册成功
JOptionPane.showMessageDialog(null, "注册成功!");
} else if (e.getSource() == cancelButton) {
// 取消按钮被点击
setContentPane(getContentPane());
setTitle("登录");
setVisible(true);
}
}
// 主函数
public static void main(String[] args) {
new LoginDemo().setVisible(true);
}
}
```
这个代码实现了一个简单的登录界面和注册界面。当用户点击登录按钮时,程序会判断用户名和密码是否正确,并给出相应的提示;当用户点击注册按钮时,程序会切换到注册界面;当用户点击注册界面的确认按钮时,程序会提示注册成功。