实验任务四:随机验证码的生成

   登录界面

程序设计思想:根据Random.java,用随机的有关类,可生成6位的验证码,然后进行判断即可。均用消息显示框实现。

程序流程图:

 

源程序:

//验证码截图

//那颖       20163448    信1605-2班

import java.util.Random;

import javax.swing.JOptionPane;  

public class RandonStr

{

    public static void main(String[] args)

    {

        String code=" ";//定义一个新的空字符串

        for(int i=1;i<=6;i++)

        {

            Random random=new Random();

            int character=random.nextInt(26)+97;//随机产生97-123之间的数

            code=code+(char)character;//将产生的数转化为char类型为小写字母

        }

        String input=JOptionPane.showInputDialog(code+" "+"请输入验证码:");//显示验证码,并提示用户输入验证码

        if(input.equals(code))//判断验证码是否正确

        {

            JOptionPane.showMessageDialog(null,"验证码正确,验证成功!","Results",JOptionPane.PLAIN_MESSAGE );

        }

        else

        {

            JOptionPane.showMessageDialog(null,"验证码错误,验证失败!","Results",JOptionPane.PLAIN_MESSAGE );

        }

    }

}

//登录界面截图

//那颖    20163448  信1605-班

import javax.swing.*;

import java.awt.*;   //导入必要的包

public class LogonInterface extends JFrame

{

    JTextField jTextField;

    JPasswordField jPasswordField;

    JLabel jLabel1,jLabel2;

    JPanel jp1,jp2,jp3;

    JButton jb1,jb2;

    public LogonInterface()

    {

        jTextField = new JTextField(12);

        jPasswordField = new JPasswordField(13);

        jLabel1 = new JLabel("用户名");

        jLabel2 = new JLabel("密   码");

        jb1 = new JButton("登录");

        jb2 = new JButton("快速注册");

        jp1 = new JPanel();

        jp2 = new JPanel();

        jp3 = new JPanel();

        

        //设置布局

        this.setLayout(new GridLayout(3,1));

        

        jp1.add(jLabel1);

        jp1.add(jTextField);//第一块面板添加用户名和文本框

        

        jp2.add(jLabel2);

        jp2.add(jPasswordField);//第二块面板添加密码和密码输入框

        

        jp3.add(jb1);

        jp3.add(jb2); //第三块面板添加确认和取消

        

        // jp3.setLayout(new FlowLayout());    //因为JPanel默认布局方式为FlowLayout,所以可以注销这段代码.

        this.add(jp1);

        this.add(jp2);

        this.add(jp3);  //将三块面板添加到登陆框上面

        //设置显示

        this.setSize(300, 200);

        //this.pack();

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setVisible(true);

        this.setTitle("登陆");

         

    }

    public static void main(String[] args){

        new LogonInterface();

    }

}

运行结果截图:

实验总结:实现验证码这个一个在于随机生成6位的验证码,一个在于判断验证码是否正确,其次,想要实现整个登录界面的实现就要用JFrame类,很多关于JFrame的类的内容不知道,所以没办法自己独立完成,那就先学会借鉴!

原文地址:https://www.cnblogs.com/-2016/p/7636285.html