9.17
生成验证码的Java程序
package lll;
import java.util.Random;
public class VerificationCodeGenerator {
public static void main(String[] args) {
String verificationCode = generateVerificationCode(6);
System.out.println("验证码:" + verificationCode);
}
public static String generateVerificationCode(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder verificationCode = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
verificationCode.append(characters.charAt(index));
}
return verificationCode.toString();
}
}
package lll;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class VerificationCodeGeneratorGUI extends JFrame {
private JTextField lengthTextField;
private JLabel verificationCodeLabel;
public VerificationCodeGeneratorGUI() {
setTitle("验证码生成器");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel lengthPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
lengthPanel.add(new JLabel("验证码长度:"));
lengthTextField = new JTextField(10);
lengthPanel.add(lengthTextField);
mainPanel.add(lengthPanel);
JPanel generatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JButton generateButton = new JButton("生成验证码");
generateButton.addActionListener(new GenerateButtonListener());
generatePanel.add(generateButton);
mainPanel.add(generatePanel);
JPanel verificationCodePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
verificationCodePanel.add(new JLabel("验证码:"));
verificationCodeLabel = new JLabel();
verificationCodePanel.add(verificationCodeLabel);
mainPanel.add(verificationCodePanel);
add(mainPanel);
setVisible(true);
}
private class GenerateButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
int length = Integer.parseInt(lengthTextField.getText());
String verificationCode = generateVerificationCode(length);
verificationCodeLabel.setText(verificationCode);
}
}
public static String generateVerificationCode(int length) {
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder verificationCode = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = random.nextInt(characters.length());
verificationCode.append(characters.charAt(index));
}
return verificationCode.toString();
}
public static void main(String[] args) {
new VerificationCodeGeneratorGUI();
}
}
module dada {
requires java.desktop;
}

浙公网安备 33010602011771号