自动生成30道小学四则运算验证码
1. 设计思想
利用JFrame从而实现,编写两个类,第二个用来实现验证码的相关操作
2. 源程序代码
//班级:信1705-2
//姓名:马旺旺
//学号:20173564
import java.awt.*;
import javax.swing.*;
public class Yanzheng extends JFrame {
private JLabel userLa;
private JLabel pwdLa;
private JLabel verCodeLa;//验证码
private JTextField userTxt;
private JPasswordField pwdTxt;
private JTextField verCodeTxt;//验证码
private JButton sureBt;
private JButton quitBt;
private Yangzhengma mp;
//构造方法
public Yanzheng()
{
Init();
}
public void Init()
{
this.setTitle("请登入");
//创建出控件对象(因为上面只是声明出来,并没有给出实际的空间)
//用户文本
userLa = new JLabel();
userLa.setText("用户名:");
userLa.setSize(60, 50);
userLa.setLocation(100, 80);
//密码文本
pwdLa = new JLabel();
pwdLa.setText("密码:");
pwdLa.setSize(50, 50);
pwdLa.setLocation(100, 120);
//用户输入框
userTxt = new JTextField();
userTxt.setSize(100, 30);
//this.setSize(width, height)
userTxt.setLocation(170, 95);
//密码输入框
pwdTxt = new JPasswordField();
pwdTxt.setSize(100, 30);
pwdTxt.setLocation(170, 135);
//登陆
sureBt = new JButton("登录");
sureBt.setSize(100, 25);
sureBt.setLocation(135, 220);
//快速注册
quitBt = new JButton("快速注册");
quitBt.setSize(100, 25);
quitBt.setLocation(135,260);
//验证码文本
verCodeLa = new JLabel();
verCodeLa.setText("验证码:");
verCodeLa.setSize(60, 50);
verCodeLa.setLocation(100,165);
//验证码文本框
verCodeTxt = new JTextField();
verCodeTxt.setSize(100, 30);
verCodeTxt.setLocation(170, 180);
//验证码
mp = new Yangzhengma();
mp.setSize(100, 30);
mp.setLocation(280, 175);
this.setLayout(null);
this.setSize(500, 400);
this.add(userLa);
this.add(pwdLa);
this.add(userTxt);
this.add(pwdTxt);
this.add(sureBt);
this.add(quitBt);
this.add(verCodeLa);
this.add(verCodeTxt);
this.add(mp);
this.setVisible(true);
}
public static void main(String[] args) {
new Yanzheng();
}
}
package 练习一;
import java.awt.*;
import java.util.*;
public class Yangzhengma extends Panel {
public void paint(Graphics g)
{
int height = 50;
int width = 90;
//验证码框背景颜色
g.setColor(Color.BLUE);
//填充验证码背景
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(0, 0, width-1, height-1);
Random r = new Random();
//设置干扰点
for(int i = 0;i<100;i++)
{
int x = r.nextInt(width)-1;
int y = r.nextInt(height)-1;
g.drawOval(x, y, 2, 2);
}
g.setFont(new Font("黑体",Font.BOLD,20));//设置验证码字体以及大小
g.setColor(Color.red);//设置验证码字体颜色
//生成随机验证码
char[] tmp = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
StringBuilder sb = new StringBuilder();
for(int i = 0;i<4;i++)
{
int pos = r.nextInt(tmp.length);
char c = tmp[pos];
sb.append(c + " ");
}
g.drawString(sb.toString(), 10, 15);//写入验证码
}
}
3. 实现结果截图
4. 实验总结
本次实验为做一个文本框软件,验证码的实质即为随机数的综合应用,添加了英文字母的应用。