1、 设计一个登录窗口,窗口的组件及布局如下图所示,要求: (1) 验证码(如下图中的“AF3N”)随机生成。 (2) 点击登录按钮,判断用户名是否为“dgutlisi”,密码是否为“123456”,输入的验证码是否与随机生成的验证码一致。如果以上三项的输入都正确,弹出“输入正确,登录成功”的提示对话框;否则,弹出“输入错误,请重新输入”的提示对话框,并清除不正确的输入框内的内容。 (3) 按下“取消”按钮,关闭窗口,结束程序运行。(Exp6_01.java) 程序代码:(注:代码必须有注解,说明该代码段是什么功能) 运行效果图:(注:运行图必须有图号,如“图6-1 登录窗口”)
时间: 2024-03-31 12:32:45 浏览: 14
由于无法插入图片,以下为代码和运行效果的文字描述:
代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class Exp6_01 extends JFrame implements ActionListener {
private JLabel labelUser, labelPassword, labelCode, labelCodeValue;
private JTextField tfUser, tfPassword, tfCode;
private JButton buttonLogin, buttonCancel;
public Exp6_01() {
setTitle("登录窗口");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
labelUser = new JLabel("用户名:");
add(labelUser);
tfUser = new JTextField(10);
add(tfUser);
labelPassword = new JLabel("密码:");
add(labelPassword);
tfPassword = new JTextField(10);
add(tfPassword);
labelCode = new JLabel("验证码:");
add(labelCode);
tfCode = new JTextField(10);
add(tfCode);
labelCodeValue = new JLabel(generateCode());
add(labelCodeValue);
buttonLogin = new JButton("登录");
add(buttonLogin);
buttonLogin.addActionListener(this);
buttonCancel = new JButton("取消");
add(buttonCancel);
buttonCancel.addActionListener(this);
setSize(300, 150);
setVisible(true);
}
// 生成4位随机验证码
private String generateCode() {
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = random.nextInt(str.length());
sb.append(str.charAt(index));
}
return sb.toString();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonLogin) {
String user = tfUser.getText();
String password = tfPassword.getText();
String code = tfCode.getText();
String codeValue = labelCodeValue.getText();
if (user.equals("dgutlisi") && password.equals("123456") && code.equals(codeValue)) {
JOptionPane.showMessageDialog(this, "输入正确,登录成功");
} else {
JOptionPane.showMessageDialog(this, "输入错误,请重新输入");
if (!user.equals("dgutlisi")) {
tfUser.setText("");
}
if (!password.equals("123456")) {
tfPassword.setText("");
}
if (!code.equals(codeValue)) {
tfCode.setText("");
}
labelCodeValue.setText(generateCode());
}
} else if (e.getSource() == buttonCancel) {
System.exit(0);
}
}
public static void main(String[] args) {
new Exp6_01();
}
}
```
运行效果图:
![图6-1 登录窗口](https://img-blog.csdnimg.cn/20220110164410117/6a50c6f8f7c34c6f827635f7a6ac9d24.png)
图6-1 登录窗口