java动态验证码实例
时间: 2023-03-03 15:36:37 浏览: 130
以下是一个使用Java实现动态验证码的示例,它使用Java的Swing库来创建GUI并生成随机验证码:
```java
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DynamicCaptcha extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private String captchaString;
private JTextField captchaTextField;
private JButton submitButton;
public DynamicCaptcha() {
generateCaptcha();
captchaTextField = new JTextField(20);
submitButton = new JButton("Submit");
submitButton.addActionListener(this);
add(captchaTextField);
add(submitButton);
}
public void generateCaptcha() {
Random random = new Random();
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
sb.append(alphabet.charAt(random.nextInt(alphabet.length())));
}
captchaString = sb.toString();
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.BOLD, 24));
g.drawString(captchaString, 100, 100);
}
public void actionPerformed(ActionEvent e) {
String input = captchaTextField.getText();
if (input.equals(captchaString)) {
System.out.println("Captcha validation successful!");
} else {
System.out.println("Captcha validation failed!");
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Dynamic Captcha");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.add(new DynamicCaptcha());
frame.setVisible(true);
}
}
```
这个示例代码创建了一个继承自JPanel的DynamicCaptcha类,它包含一个生成验证码的方法generateCaptcha()和一个重写paint()方法以在面板上绘制验证码。在main()方法中,它创建了一个JFrame并将DynamicCaptcha实例添加到其中以显示GUI。用户可以输入验证码并单击提交按钮来验证它是否正确。
阅读全文