hhhhhhomework 验证码界面(非全部自己完成)

import javax.swing.*;//import  代表“引入”
                     //javax.swing 代表“路径” (在javax文件夹下的swing文件夹)
                     //*  代表“全部”
import java.awt.*;   //
import java.awt.event.ActionEvent;//是JAVA AWT抽象窗口工具集包的一部分,用于处理用户执行的动作事件
import java.awt.event.ActionListener;//是否来判断点击登录后密码和账号是否正确
import java.util.Random;//随机数包

public class RandomGraphic {
    private static final String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//初始化一个字符串
    private static final int codeLength = 6;//代表长度为6的验证码
    private static String currentVerificationCode;//记录正确的验证码

    public static void main(String[] args) {
        JFrame frame = new JFrame("随机验证码");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 200);

        JPanel panel = new JPanel(new GridLayout(4, 1));
        frame.add(panel);

        JLabel codeLabel = new JLabel();
        panel.add(codeLabel);

        JTextField inputField = new JTextField();
        panel.add(inputField);

        JButton submitButton = new JButton("提交");
        panel.add(submitButton);

        JLabel hintLabel = new JLabel("请输入验证码");
        panel.add(hintLabel);

        generateAndSetVerificationCode(codeLabel);

        submitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String userInput = inputField.getText().trim();
                if (userInput.equals(currentVerificationCode)) {
                    JOptionPane.showMessageDialog(frame, "验证码正确!程序即将退出。");
                    System.exit(0);
                } else {
                    JOptionPane.showMessageDialog(frame, "验证码错误,请重新输入!", "错误", JOptionPane.ERROR_MESSAGE);
                    generateAndSetVerificationCode(codeLabel);
                }
                inputField.setText("");
            }
        });

        frame.setVisible(true);
    }

    public static void generateAndSetVerificationCode(JLabel codeLabel) {
        currentVerificationCode = generateVerificationCode(codeLength);
        codeLabel.setText("验证码: " + currentVerificationCode);
    }

    public static String generateVerificationCode(int length) {
        Random random = new Random();
        StringBuilder codeBuilder = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            char randomChar = characters.charAt(index);
            codeBuilder.append(randomChar);
        }

        return codeBuilder.toString();
    }
}

 

posted @ 2023-09-18 13:03  beiqu  阅读(4)  评论(0编辑  收藏  举报