java gui界面设计 登录界面设计及事件 利用hashmap储存账号密码,判断密码是否正确
时间: 2023-08-16 14:07:33 浏览: 42
好的,以下是一个简单的Java GUI登录界面设计及事件处理代码,使用HashMap存储账号密码,实现密码的正确性验证:
```
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.HashMap;
public class LoginFrame extends JFrame implements ActionListener {
JLabel userLabel, passLabel;
JTextField userText;
JPasswordField passText;
JButton loginButton, clearButton;
HashMap<String, String> userMap;
public LoginFrame() {
setTitle("登录");
setSize(300, 150);
setLocationRelativeTo(null);
userMap = new HashMap<>();
userMap.put("admin", "admin123");
userLabel = new JLabel("用户名:");
passLabel = new JLabel("密码:");
userText = new JTextField(10);
passText = new JPasswordField(10);
loginButton = new JButton("登录");
clearButton = new JButton("清空");
JPanel panel = new JPanel(new GridLayout(3, 2));
panel.add(userLabel);
panel.add(userText);
panel.add(passLabel);
panel.add(passText);
panel.add(loginButton);
panel.add(clearButton);
add(panel, BorderLayout.CENTER);
loginButton.addActionListener(this);
clearButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userText.getText();
String password = new String(passText.getPassword());
if (userMap.containsKey(username) && userMap.get(username).equals(password)) {
JOptionPane.showMessageDialog(this, "登录成功!");
} else {
JOptionPane.showMessageDialog(this, "用户名或密码错误!");
}
} else if (e.getSource() == clearButton) {
userText.setText("");
passText.setText("");
}
}
public static void main(String[] args) {
LoginFrame frame = new LoginFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
```
代码主要分为以下几部分:
1. 创建GUI界面的各个组件,包括标签、文本框、密码框、按钮等。
2. 创建一个HashMap,用于存储账号密码。
3. 在构造方法中添加各个组件,并为登录按钮和清空按钮添加事件监听器。
4. 实现ActionListener接口,处理按钮点击事件。
5. 在登录按钮点击事件中,获取用户输入的用户名和密码,使用HashMap判断密码是否正确,并弹出相应提示框。
希望能对你有所帮助!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)