package com.ah.testjava.validatecode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.util.Random; import javax.swing.JFrame;
import javax.swing.JPanel; public class 验证码 extends JFrame { public 验证码() {
setVisible(true);
setSize(800, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE); MyJp jp = new MyJp();
this.add(jp);
} public static void main(String[] args) {
new 验证码();
}
}
package com.ah.testjava.validatecode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random; import javax.swing.JPanel; public class MyJp extends JPanel {
public MyJp(){ } @Override
public void paintComponent(Graphics g) {
BufferedImage vc = createVCode();
g.drawImage(vc,0,0,100,30,null);
} public BufferedImage createVCode() {
int nStrfontSize=30;
int nStrY=30;
int width = 100;
int height = 30;
// 创建一个画布
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
// 创建画笔
Graphics g = image.getGraphics();
// 设置画笔颜色
g.setColor(Color.white);
// 填充背景颜色
g.fillRect(0, 0, width, height);
// 创建将要输出的内容
char[] words = "01234567890abcdefghijklmn马蓉王宝强赵薇宋哲".toCharArray();
// 创建随机对象(用于随机选择要生成的验证码和颜色)
Random rnd = new Random(); // 画圆点
for (int i = 0; i < 200; i++) {
// 设置画笔颜色
g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd
.nextInt(255)));
// 画椭圆
g.drawOval(rnd.nextInt(width), rnd.nextInt(height), 1, 1);
} // 创建一个临时变量用于拼接生成的验证码
String sessionCode = ""; // 生成4位验证码
for (int i = 0; i < 4; i++) {
// 使用画笔,在画布上写字
g.setColor(new Color(rnd.nextInt(255), rnd.nextInt(255), rnd
.nextInt(255)));
// 设置字体相关
g.setFont(new Font("微软雅黑", Font.BOLD, nStrfontSize));
// 获取当前产生的验证码(单个)
String currentCode = words[rnd.nextInt(words.length)] + "";
// 每次将生成的结果拼接起来
sessionCode += currentCode;
// 在画布上写文字,并且设置文字的 横坐标和纵坐标
g.drawString(currentCode, i * 20 + 10, nStrY); }
return image; }
}

验证码I-LMLPHP

05-01 01:13