亲宝软件园·资讯

展开

Swing验证码 Swing图形界面实现可动态刷新的验证码

Joker_Ye 人气:0
想了解Swing图形界面实现可动态刷新的验证码的相关内容吗,Joker_Ye在本文为您仔细讲解Swing验证码的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Swing,验证码,下面大家一起来学习吧。

不多,code代码如下:

import java.awt.Color; 
import java.awt.Font; 
import java.awt.Graphics; 
import java.awt.Toolkit; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.util.Random; 
import javax.swing.JFrame; 
 
public class CheckCode extends JFrame { 
private static Random random = new Random(); 
private int width = 53;//验证码宽度 
private int height =25;//验证码高度 
private int font_size = 20;//验证码颜色 
private int x = 100;//验证码所在窗体X坐标 
private int y = 100;//验证码所在窗体Y坐标 
private int jam = 5;//干扰元素 建议使用 4~7 之间的数字 
private String code = "";//保存验证码 
 
public CheckCode(){//初始化窗体信息 
super("验证码"); 
setVisible(true); 
setBounds((Toolkit.getDefaultToolkit().getScreenSize().width-300)/2, (Toolkit.getDefaultToolkit().getScreenSize().height-300)/2, 300, 200); 
setDefaultCloseOperation(EXIT_ON_CLOSE); 
addMouseListener(new MouseAdapter() { 
public void mouseClicked(MouseEvent e) { 
repaint(); 
} 
}); 
} 
 
public Color getRandomColor(){//获得随机颜色 
int R=random.nextInt(255),G=random.nextInt(255),B=random.nextInt(255); 
return new Color(R,G,B); 
} 
 
public String getRandomString(){//获得验证码 
int num = random.nextInt(9); 
code = num+""; 
return num+""; 
} 
 
public void checkCode(Graphics g){// 绘画验证码 
drawBorder(g);  
drawCode(g); 
drawJam(g); 
} 
 
public void drawBorder(Graphics g){//绘画边框和背景 
Color gc = g.getColor(); 
g.setColor(Color.WHITE); 
g.fillRect(x, y, width, height); 
g.setColor(Color.BLACK); 
g.drawRect(x, y, width, height); 
g.setColor(gc); 
} 
 
public void drawCode(Graphics g){//绘画验证码内容 
Color gc = g.getColor(); 
for(int i=0;i<4;i++){ 
g.setColor(getRandomColor()); 
g.setFont(new Font("宋体",Font.BOLD,font_size)); 
g.drawString(getRandomString(), x+5+(i*12), y+font_size); 
} 
g.setColor(gc); 
} 
 
public void drawJam(Graphics g){//绘画干扰元素 
Color gc = g.getColor(); 
for(int i=0;i<jam;i++){ 
g.setColor(getRandomColor()); 
g.drawLine(x+random.nextInt(width), y+random.nextInt(height), x+random.nextInt(width), y+random.nextInt(height)); 
} 
g.setColor(gc); 
} 
 
public void paint(Graphics g) { 
Color c = g.getColor(); 
g.drawString("单击可刷新验证码", 30, 50); 
checkCode(g); 
g.setColor(c); 
} 
 
public static void main(String[] args) { 
new CheckCode(); 
} 
} 

加载全部内容

相关教程
猜你喜欢
用户评论