简单随机验证码的生成
一 代码
/** * * @ClassName: TestVerificationCode * * @Description: 随机验证码的实现 * */ import java.awt.*; import java.awt.event.*; import java.util.Random; import javax.swing.*; public class TestVerificationCode { public static void main(String[] args) { JFrame frame = new JFrame("登录测试"); JButton b1 = new JButton("登陆"); JButton b2 = new JButton("注册"); JPanel center = new JPanel(); center.setLayout(new GridLayout(0, 1, 5, 5)); JPanel center1 = new JPanel(); JPanel center2 = new JPanel(); JPanel center3 = new JPanel(); JPanel west = new JPanel(); JTextField t1 = new JTextField(10); JPasswordField t2 = new JPasswordField(10); JTextField t3 = new JTextField(5); center1.setLayout(new GridLayout(1, 0)); // 仅限1行,不限列 center2.setLayout(new GridLayout(1, 0)); center3.setLayout(new GridLayout(1, 0, 5, 5)); center1.add(t1); center2.add(t2); center3.add(t3); ValidCode valid = new ValidCode(); center3.add(valid); center.add(center1); center.add(center2); center.add(center3); west.setLayout(new GridLayout(0, 1)); west.add(new JLabel("账 号:")); west.add(new JLabel("密 码:")); west.add(new JLabel("验证码:")); JPanel south = new JPanel(); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (t3.getText().equals(valid.getCode())) JOptionPane.showMessageDialog(null, "验证成功"); else { JOptionPane.showMessageDialog(null, "验证失败"); valid.nextCode(); } } }); south.add(b1); south.add(b2); frame.setSize(275, 240); frame.add(west, BorderLayout.WEST); JLabel mes = new JLabel(" 欢迎登陆邮箱"); mes.setFont(new Font("黑体", Font.BOLD, 25)); frame.add(mes, BorderLayout.NORTH); frame.add(center, BorderLayout.CENTER); frame.add(south, BorderLayout.SOUTH); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class ValidCode extends JPanel { String code; private Random random = new Random(); public ValidCode() { setSize(100, 40); this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { setSize(100, 40); nextCode(); } }); } public String getCode() { return code; } void generateCode() { char[] codes = new char[5]; for (int i = 0; i < 5; i++) { if (random.nextBoolean()){ codes[i] = (char) (random.nextInt(26) + 65); } else { codes[i] = (char) (random.nextInt(26) + 97); } } this.code = new String(codes); } public void paint(Graphics g) { if (this.code == null) { generateCode(); } Font myFont = new Font("Arial", Font.BOLD | Font.ITALIC, 25); g.setFont(myFont); g.setColor(Color.WHITE); g.fillRect(0, 0, 100, 40); g.setColor(Color.BLACK); g.drawRect(0, 0, 99, 39); g.setColor(Color.LIGHT_GRAY); for (int i = 0; i < 100; i++) { int x = random.nextInt(100 - 1); int y = random.nextInt(40 - 1); int x1 = random.nextInt(100 - 10) + 10; int y1 = random.nextInt(40 - 4) + 4; g.drawLine(x, y, x1, y1); } g.setColor(Color.RED); for (int i = 0; i < 5; i++) { g.drawString(code.charAt(i) + "", 16 * i + 10, 25); } } public void nextCode() { generateCode(); repaint(); } }
二 运行
上一篇:
IDEA上Java项目控制台中文乱码