java 练习之生成随机四位验证码
作者:互联网
java 小demo — 随机生成四位验证码
import javax.swing.*;
import java.awt.*;
import java.util.Random;
/**
* @author yk.ddm
* @createDate 2021-01-05 12:18
*/
public class Test {
public static void main(String[] args) {
JFrame jf = new JFrame();
JPanel jPanel = new Mypanel();
jf.add(jPanel);
jf.setSize(200,100);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
Mypanel mypanel =new Mypanel();
Test05 t = new Test05();
String s = t.getNumber();
}
}
class Mypanel extends JPanel{
static String s;
@Override
public void paint(Graphics g) {
//设置验证码的宽高
int width = 160;
int height = 40;
g.setColor(Color.LIGHT_GRAY);//背景颜色
g.fillRect(0, 0, width -1, height -1);//背景填充
g.setColor(Color.BLACK);//边框颜色
g.drawRect(0, 0, width -1, height -1);//绘制边框
//绘制干扰点
Random random = new Random();
for (int i = 0; i < 100; i++) {
int x = random.nextInt(width) - 2;
int y = random.nextInt(height) - 2;
g.drawOval(x, y, 2, 2);
}
//开始对验证码字体进行设置
g.setFont(new Font("黑体",Font.BOLD,32));//字体
g.setColor(Color.BLUE);//颜色
//设置一个数组来当验证码的词库
char [] arr = ("0123456789").toCharArray();
//实例化一个StringBuilder对象来生成随机验证码
StringBuilder sb = new StringBuilder();
//循环生成4个随机数
for (int i = 0; i < 4; i++) {
//生成一个随机位置
int position = random.nextInt(arr.length);
//获取到这个位置的字符
char c = arr[position];
//将字符添加到StringBuilder对象里面,并且加一个空格保持间隔
sb.append(c+"");
}
//写入验证码,调用sb的toString()方法将其转换为一个String对象进行写入
g.drawString(sb.toString(), 20, 30);
//新建一个String类型的变量来存储已经好了的验证码,用来判断用户输入的验证码是否正确
String s = sb.toString();
this.s = sb.toString();
// Mypanel.s = sb.toString();
System.out.println(Mypanel.s);
// System.out.println(s);
Test05 t = new Test05();
t.setNumber(s);
}
}
class Test05 {
String Number ;
public String getNumber() {
return Number;
}
public void setNumber(String number) {
Number = number;
}
}
标签:java,String,int,验证码,sb,new,四位,Mypanel 来源: https://blog.csdn.net/yk_ddm/article/details/112226075