import java.awt.*;
import java.util.Random;
import javax.swing.*;
import java.awt.event.*;
public class SU {
public static void main(String[] args) {
final Frame frame = new Frame("验证码"); // 创建Frame对象
final Panel panel = new MyPanel(); // 创建Canvas对象
frame.add(panel);
frame.setSize(200, 100);
// 将Frame窗口居中
frame.setLocationRelativeTo(null);
frame.setVisible(true);
MyWindowListener mw=new MyWindowListener();
frame.addWindowListener(mw);
}
}
class MyPanel extends Panel {
public void paint(Graphics g) {
int width = 180; // 定义验证码图片的宽度
int height = 60; // 定义验证码图片的高度
g.setColor(Color.LIGHT_GRAY); // 设置上下文颜色
g.fillRect(0, 0, width, height); // 填充验证码背景
g.setColor(Color.BLACK); // 设置上下文颜色
g.drawRect(0, 0, width - 1, height - 1); // 绘制边框
// 绘制干扰点
Random r = new Random();
for (int i = 0; i < 100; i++) {
int x = r.nextInt(width)-1;
int y = r.nextInt(height)-1;
g.drawOval(x, y, 2, 2);
}
g.setFont(new Font("楷书", Font.BOLD, 30)); // 设置验证码字体
g.setColor(Color.BLUE); // 设置验证码颜色
// 产生随机验证码
char[] chars = ("0123456789abcdefghijkmnopqrstuvwxyzABCDEFG"
+ "HIJKLMNPQRSTUVWXYZ").toCharArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int pos = r.nextInt(chars.length);
char c = chars[pos];
sb.append(c + " ");
}
g.drawString(sb.toString(), 20, 30); // 写入验证码
}
}
//关窗口
class MyWindowListener implements WindowListener {
// 监听器监听事件对象作出处理
public void windowClosing(WindowEvent e) {
Window window = e.getWindow();
window.setVisible(false);
// 释放窗口
window.dispose();
}
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
}
AWT绘图(验证码)
最新推荐文章于 2024-02-23 15:09:51 发布