编写程序,利用JTextField和JPasswordField分别接收用户输入的用户名和密码,并对用户输入的密码进行检验。对于每个用户名有3次输入密码机会。(用匿名类的方式来编写)
时间: 2024-03-16 10:44:38 浏览: 75
密码输入检验程序
以下是使用匿名类的Java代码:
```java
import javax.swing.*;
import java.awt.event.*;
public class LoginFrame extends JFrame {
private JTextField usernameField;
private JPasswordField passwordField;
private int loginAttempts;
public LoginFrame() {
super("Login");
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new JLabel("Username:"));
usernameField = new JTextField(20);
panel.add(usernameField);
panel.add(new JLabel("Password:"));
passwordField = new JPasswordField(20);
panel.add(passwordField);
JButton loginButton = new JButton("Login");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkLogin()) {
JOptionPane.showMessageDialog(LoginFrame.this, "Login successful!");
dispose();
}
else if (++loginAttempts == 3) {
JOptionPane.showMessageDialog(LoginFrame.this, "Too many login attempts. Program will exit.");
System.exit(0);
}
else {
JOptionPane.showMessageDialog(LoginFrame.this, "Invalid username or password. Please try again.");
passwordField.setText("");
}
}
});
panel.add(loginButton);
setContentPane(panel);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private boolean checkLogin() {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// Perform some validation here
// For example, check against a database of users and passwords
// For simplicity, we just check if the username is "admin" and the password is "password"
return username.equals("admin") && password.equals("password");
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
这个程序创建了一个登录窗口,并提供了一个文本框和一个密码框用于输入用户名和密码。当用户点击“Login”按钮时,程序将检查输入的用户名和密码是否正确。如果不正确,程序将显示一个错误消息,并清空密码框。如果连续3次输入错误的密码,程序将退出。
阅读全文