import javax.swing.;
import java.awt.;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class CaptchaGUI extends JFrame {
private JLabel captchaLabel;
private JTextField inputField;
private JButton submitButton;
private String captchaText;
public CaptchaGUI() {
setTitle("请输入验证码");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 创建主面板
JPanel mainPanel = new JPanel(new BorderLayout());
// 生成验证码
captchaText = generateCaptcha();
// 创建验证码标签
captchaLabel = new JLabel(captchaText);
captchaLabel.setFont(new Font("Monospaced", Font.BOLD, 30));
captchaLabel.setHorizontalAlignment(SwingConstants.CENTER);
mainPanel.add(captchaLabel, BorderLayout.NORTH);
// 创建输入框和提交按钮
JPanel inputPanel = new JPanel(new FlowLayout());
inputField = new JTextField(10);
inputPanel.add(inputField);
submitButton = new JButton("提交");
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
checkCaptcha();
}
});
inputPanel.add(submitButton);
mainPanel.add(inputPanel, BorderLayout.CENTER);
// 添加主面板到窗口
add(mainPanel);
}
private String generateCaptcha() {
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < 4; i++) {
captcha.append(chars.charAt(random.nextInt(chars.length())));
}
return captcha.toString();
}
private void checkCaptcha() {
String userInput = inputField.getText();
if (userInput.equals(captchaText)) {
JOptionPane.showMessageDialog(this, "验证码正确!");
} else {
JOptionPane.showMessageDialog(this, "验证码错误!请重试。");
captchaText = generateCaptcha();
captchaLabel.setText(captchaText);
inputField.setText("");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CaptchaGUI().setVisible(true);
}
});
}
}
标签:captchaLabel,验证码,private,add,captchaText,new
From: https://www.cnblogs.com/bawangji666/p/18440660