编写程序,利用JTextField和JPasswordField分别接收用户输入的用户名和密码,并对用户输入的密码进行检验。对于每个用户名有三次密码输入机会
时间: 2023-06-18 15:06:49 浏览: 161
下面是一个简单的Java程序示例,演示如何使用JTextField和JPasswordField接收用户输入的用户名和密码,并对密码进行检验,每个用户名有三次密码输入机会:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class LoginFrame extends JFrame implements ActionListener {
private JTextField usernameField;
private JPasswordField passwordField;
private JLabel statusLabel;
private int remainingAttempts = 3; // remaining password attempts
public LoginFrame() {
super("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
// create username and password input fields
JPanel inputPanel = new JPanel(new GridLayout(2, 2));
JLabel usernameLabel = new JLabel("Username:");
inputPanel.add(usernameLabel);
usernameField = new JTextField();
inputPanel.add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
inputPanel.add(passwordLabel);
passwordField = new JPasswordField();
passwordField.addActionListener(this);
inputPanel.add(passwordField);
add(inputPanel, BorderLayout.CENTER);
// create login button
JButton loginButton = new JButton("Login");
loginButton.addActionListener(this);
add(loginButton, BorderLayout.SOUTH);
// create status label
statusLabel = new JLabel("Please enter your username and password.");
add(statusLabel, BorderLayout.NORTH);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String(passwordField.getPassword());
// check if password is correct
if (authenticate(username, password)) {
statusLabel.setText("Welcome, " + username + "!");
remainingAttempts = 3; // reset remaining attempts
passwordField.setText(""); // clear password field
} else {
remainingAttempts--;
if (remainingAttempts == 0) {
statusLabel.setText("Login failed. You have no more attempts.");
usernameField.setEditable(false);
passwordField.setEditable(false);
} else {
statusLabel.setText("Login failed. You have " + remainingAttempts + " attempts remaining.");
passwordField.setText(""); // clear password field
}
}
}
private boolean authenticate(String username, String password) {
// check if username and password are correct
// replace with your own authentication logic
if (username.equals("admin") && password.equals("password")) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
new LoginFrame();
}
}
```
在这个程序中,我们创建了一个继承自JFrame的LoginFrame类,它包含一个JTextField和一个JPasswordField用于接收用户名和密码输入,以及一个JLabel用于显示状态信息。我们为JPasswordField添加了ActionListener,以便在用户按下“Enter”键时触发登录。当用户输入用户名和密码并点击登录按钮时,我们使用authenticate()方法检查密码是否正确。如果密码正确,我们显示欢迎消息并重置剩余尝试次数。如果密码错误,我们减少剩余尝试次数并显示相应的错误消息。如果剩余尝试次数为零,我们禁用用户名和密码输入字段。