java随机生成四位字符验证码(使用Graphics绘图类)

来源:互联网 发布:linux 更新grub命令 编辑:程序博客网 时间:2024/05/17 07:37

/*使用绘图类Graphics实现随机生成四位验证码,随机颜色,随机字体*/

package com.itany.graphic;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.util.Random;

/*

 * 随机数

 */

public class ValidateCode {

//随机字符

privatestatic StringBuilder sb =new StringBuilder();

//随机类

privatestatic Random random =new Random();

//范围参数

//字体 

privatestatic String[] fontName={"幼圆","微软雅黑","新宋体","方正姚体","方正舒体","楷体","隶书","黑体"};

//样式

privatestaticint[] fontStyle={Font.BOLD,Font.ITALIC,Font.ROMAN_BASELINE};

//大小

privatestaticint[] fontSize={26,28,30,32,34,36};

//字符库

privatestatic String chs="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

publicstaticvoid init(Graphics g){

//画矩形

g.setColor(Color.LIGHT_GRAY);

g.fill3DRect(5,5,130,50,false);

//随机四个数

randomNum(g);

//画干扰线

randomLine(g);

}


//画干扰线

privatestaticvoid randomLine(Graphics g) {

for(int i=0;i<4;i++){

g.setColor(randomColor());

g.drawLine(random.nextInt(131)+5, random.nextInt(51)+5, random.nextInt(131)+5, random.nextInt(51)+5);

}

}


/*

* 随机色

*/

privatestatic Color randomColor() {

returnnew Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));

}


/*

* 随机数

*/

privatestaticvoid randomNum(Graphics g) {

String numStr = null;

for(int i=0;i<4;i++){

numStr = randomChar();

sb.append(numStr);

g.setColor(randomColor());

g.setFont(randomFont());

g.drawString(numStr, 30+i*20,40);

}

}

/*

* 随机码

*/

publicstatic String getCode(){

return sb.toString();

}


/*

* 随机字体

*/

privatestatic Font randomFont() {

int size = fontSize[random.nextInt(fontSize.length)];

int style =fontStyle[random.nextInt(fontStyle.length)] ;

String name=fontName[random.nextInt(fontName.length)];

Font f = new Font(name,style,size);

return f;

}


/*

*随机字符串

*/

privatestatic String randomChar() {

return chs.charAt(random.nextInt(chs.length()))+"";

}


}


调用方法如下:

JPanel pan = new JPanel(){

protected void paintComponent(Graphics g){

ValidateCode.init(g);//调用类方法初始化验证码

System.out.printIn(ValidateCode.getCode().toUpperCase());

}


}



1 0
原创粉丝点击