温馨提示×

如何在Java中实现点击验证码

小樊
106
2024-08-09 08:54:37
栏目: 编程语言

在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的黑色方块作为验证码。当用户点击窗口时,判断点击的位置是否在验证码方块内,如果在则验证成功,否则验证失败,并重新生成新的验证码。

0