在Java中實現點擊驗證碼通常需要使用GUI庫來創建驗證碼圖像并監聽用戶的點擊事件。以下是一個簡單的示例代碼來實現點擊驗證碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
public class ClickCaptcha extends JFrame {
private static final int WIDTH = 200;
private static final int HEIGHT = 100;
private int x;
private int y;
public ClickCaptcha() {
setTitle("Click Captcha");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = new Random().nextInt(WIDTH);
y = new Random().nextInt(HEIGHT);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int clickX = e.getX();
int clickY = e.getY();
if (clickX >= x && clickX <= x + 20 && clickY >= y && clickY <= y + 20) {
JOptionPane.showMessageDialog(null, "Verification successful!");
} else {
JOptionPane.showMessageDialog(null, "Verification failed!");
}
x = new Random().nextInt(WIDTH);
y = new Random().nextInt(HEIGHT);
repaint();
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, 20, 20);
}
public static void main(String[] args) {
ClickCaptcha clickCaptcha = new ClickCaptcha();
clickCaptcha.setVisible(true);
}
}
在這個示例中,我們創建了一個繼承自JFrame的ClickCaptcha類,窗口大小為200x100。在窗口內部隨機生成一個20x20的黑色方塊作為驗證碼。當用戶點擊窗口時,判斷點擊的位置是否在驗證碼方塊內,如果在則驗證成功,否則驗證失敗,并重新生成新的驗證碼。