在Java中實現滑動驗證碼可以通過以下步驟:
以下是一個簡單的示例代碼實現滑動驗證碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SlideCaptcha extends JFrame {
private JPanel captchaPanel;
private JLabel slider;
private int x, y;
public SlideCaptcha() {
captchaPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 畫驗證碼圖片
g.setColor(Color.BLUE);
g.fillRect(100, 100, 200, 100);
// 添加滑塊
slider = new JLabel(">>>");
slider.setBounds(100, 100, 50, 100);
slider.setBackground(Color.RED);
slider.setOpaque(true);
captchaPanel.add(slider);
}
};
captchaPanel.setLayout(null);
captchaPanel.setSize(400, 200);
captchaPanel.setBackground(Color.WHITE);
captchaPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
}
@Override
public void mouseDragged(MouseEvent e) {
int offsetX = e.getX() - x;
int offsetY = e.getY() - y;
slider.setLocation(slider.getX() + offsetX, slider.getY());
x = e.getX();
y = e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
if (slider.getX() == 300) {
JOptionPane.showMessageDialog(null, "驗證通過");
} else {
JOptionPane.showMessageDialog(null, "驗證失敗");
slider.setLocation(100, 100);
}
}
});
getContentPane().add(captchaPanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setVisible(true);
}
public static void main(String[] args) {
new SlideCaptcha();
}
}
通過這個示例代碼,你可以創建一個簡單的滑動驗證碼實現。當用戶拖動滑塊到指定位置時,驗證通過,否則驗證失敗。