用Java.swing写一个生成从“0123456789abcdefghijkmnopqrstuvwxyzABCDEFG”中每次产生四个随机数作为验证码的程序
时间: 2023-11-27 21:03:28 浏览: 71
好的,下面是Java.swing生成验证码的程序代码:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class VerifyCode extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private final String VERIFY_CODES = "0123456789abcdefghijkmnopqrstuvwxyzABCDEFG";// 验证码字符集
private final int VERIFY_SIZE = 4;// 验证码长度
private JPanel jp;
private JButton jb;
private String verifyCode;
public VerifyCode() {
setTitle("验证码");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp = new JPanel();
jp.setBackground(Color.WHITE);
add(jp, BorderLayout.CENTER);
jb = new JButton("生成验证码");
jb.addActionListener(this);
add(jb, BorderLayout.SOUTH);
setVisible(true);
}
private String generateVerifyCode() {
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < VERIFY_SIZE; i++) {
sb.append(VERIFY_CODES.charAt(rand.nextInt(VERIFY_CODES.length())));
}
return sb.toString();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jb) {
verifyCode = generateVerifyCode();
jp.repaint();
}
}
public static void main(String[] args) {
new VerifyCode();
}
class VerifyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.BLACK);
g.setFont(new Font("Times New Roman", Font.BOLD, 20));
g.drawString(verifyCode, 60, 60);
}
}
}
```
这个程序会在窗口中生成一个“生成验证码”的按钮,点击它可以生成一个由指定字符集中的字符组成的长度为4的随机字符串作为验证码,并在窗口中显示出来。
阅读全文