java 图片滑动验证码_java实现图片滑动验证
时间: 2023-09-16 16:14:30 浏览: 121
以下是一个简单的 Java 图片滑动验证码的示例代码,使用 Java Swing 库实现:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
public class ImageSliderVerificationCode extends JFrame {
private static final long serialVersionUID = 1L;
private final int WIDTH = 400;
private final int HEIGHT = 300;
private final int BLOCK_SIZE = 50;
private Image bgImage;
private Image blockImage;
private int blockX;
private int blockY;
private int mouseX;
private int mouseY;
private boolean isDragging;
public ImageSliderVerificationCode() {
setTitle("Image Slider Verification Code");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLocationRelativeTo(null);
bgImage = new ImageIcon("background.jpg").getImage();
blockImage = new ImageIcon("block.png").getImage();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getX() >= blockX && e.getX() <= blockX + BLOCK_SIZE &&
e.getY() >= blockY && e.getY() <= blockY + BLOCK_SIZE) {
isDragging = true;
mouseX = e.getX();
mouseY = e.getY();
}
}
public void mouseReleased(MouseEvent e) {
isDragging = false;
if (blockX >= WIDTH - BLOCK_SIZE) {
JOptionPane.showMessageDialog(null, "Verification passed!");
System.exit(0);
} else {
blockX = 0;
blockY = new Random().nextInt(HEIGHT - BLOCK_SIZE);
repaint();
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if (isDragging) {
blockX += e.getX() - mouseX;
blockY += e.getY() - mouseY;
if (blockX < 0) {
blockX = 0;
}
if (blockX > WIDTH - BLOCK_SIZE) {
blockX = WIDTH - BLOCK_SIZE;
}
if (blockY < 0) {
blockY = 0;
}
if (blockY > HEIGHT - BLOCK_SIZE) {
blockY = HEIGHT - BLOCK_SIZE;
}
mouseX = e.getX();
mouseY = e.getY();
repaint();
}
}
});
}
public void paint(Graphics g) {
g.drawImage(bgImage, 0, 0, null);
g.drawImage(blockImage, blockX, blockY, null);
}
public static void main(String[] args) {
ImageSliderVerificationCode verCode = new ImageSliderVerificationCode();
verCode.setVisible(true);
}
}
```
此代码将生成一个包含背景图片和滑块图片的窗口。当用户按住滑块图片并拖动它时,窗口将显示移动后的滑块图片。如果用户将滑块图片拖动到窗口的右边缘,则显示验证通过的消息并退出程序。否则,滑块图片将被重置到窗口的左侧,并随机在窗口的垂直方向上移动。
阅读全文