本文实例为大家分享了Swing实现可动态刷新的验证码的具体代码,供大家参考,具体内容如下
不多,code代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
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(); } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。