java管理员和用户登录
时间: 2023-10-30 19:04:54 浏览: 14
Java管理员和用户登录可以通过一个简单的登录界面来实现。以下是一个简单的示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Login extends JFrame implements ActionListener {
// 创建组件
JLabel userLabel = new JLabel("用户名");
JLabel passLabel = new JLabel("密 码");
JTextField userText = new JTextField(20);
JPasswordField passText = new JPasswordField(20);
JButton loginButton = new JButton("登录");
JButton resetButton = new JButton("重置");
public Login() {
setTitle("登录界面");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 设置布局
setLayout(new GridLayout(3, 2));
// 添加组件
add(userLabel);
add(userText);
add(passLabel);
add(passText);
add(loginButton);
add(resetButton);
// 添加监听器
loginButton.addActionListener(this);
resetButton.addActionListener(this);
setVisible(true);
}
// 监听事件
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String user = userText.getText();
String password = new String(passText.getPassword());
// 校验用户名和密码
if (user.equals("admin") && password.equals("admin")) {
JOptionPane.showMessageDialog(null, "管理员登录成功!");
} else if (user.equals("user") && password.equals("user")) {
JOptionPane.showMessageDialog(null, "用户登录成功!");
} else {
JOptionPane.showMessageDialog(null, "用户名或密码错误!");
}
// 清空输入框
userText.setText("");
passText.setText("");
}
if (e.getSource() == resetButton) {
userText.setText("");
passText.setText("");
}
}
public static void main(String[] args) {
new Login();
}
}
```
这个示例中,我们使用了 `JFrame` 来创建一个窗口,并在窗口中添加了用户名和密码的输入框、登录按钮和重置按钮。当用户点击登录按钮时,程序会读取输入框中的用户名和密码,并进行校验。如果用户名和密码正确,则弹出提示框显示登录成功,否则弹出提示框显示用户名或密码错误。当用户点击重置按钮时,输入框中的内容会被清空。