今天使用java语言简单设计了一个有图形化窗口的验证码生成器,使用到了swing作为图形化窗口界面,BufferedImage生成验证码图片,ActionEvent与ActionListener生成监听器执行按钮功能,使用Random生成随机数;
源代码如下:
import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.util.Random;
public class CaptchaGenerator extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel captchaLabel;
private JButton generateButton;
public CaptchaGenerator() {
setTitle("验证码生成器");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setLayout(new FlowLayout());
captchaLabel = new JLabel();
captchaLabel.setFont(new Font("Arial", Font.BOLD, 24));
captchaLabel.setPreferredSize(new Dimension(200, 60));
add(captchaLabel);
generateButton = new JButton("生成验证码");
generateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String captchaText = generateCaptcha(4);
BufferedImage captchaImage = createCaptchaImage(captchaText);
captchaLabel.setIcon(new ImageIcon(captchaImage));
}
});
add(generateButton);
}
private String generateCaptcha(int length) {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder captcha = new StringBuilder();
Random random = new Random();
for (int i = 0; i < length; i++) {
int index = random.nextInt(chars.length());
captcha.append(chars.charAt(index));
}
return captcha.toString();
}
private BufferedImage createCaptchaImage(String captchaText) {
BufferedImage image = new BufferedImage(200, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 200, 60);
g2d.setColor(Color.BLACK);
g2d.setFont(new Font("Arial", Font.BOLD, 40));
g2d.drawString(captchaText, 10, 40);
g2d.dispose();
return image;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
CaptchaGenerator generator = new CaptchaGenerator();
generator.setVisible(true);
}
});
}
}
代码首先使用JFrame创建一个窗口,并使用Dimension函数设置长宽;
再使用JButton创建一个按钮,按钮功能为生成验证码;
创建generateCaptcha方法,作用为生成四位验证码,并且验证码内容为26个字母大小写以及1至9的阿拉伯数字,返回值为String类型的四位验证码;
使用JLabel将生成的验证码显示在界面内,创建createCaptchaImage方法,作用为生成有验证码的图像,使用setColor设置背景为白色字体为黑色,返回值为BufferedImage类型的对象;