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.M ...
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();
}
}