Java 图片验证码的实现和模拟简单的登录

版权声明:文章版权归作者所有,请不要随意转载抄袭,情节严重,追究法律责任!! https://blog.csdn.net/Ibelievesunshine/article/details/84799310

 MainFrame类主要实现了GUI的界面和简单的验证逻辑 

package com.application

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class MainFrame extends JFrame {
    private static final long serialVersionUID = 6760471507923160452L;
    private JTextField codeText;
    private JPasswordField pwdText;
    private JTextField nameText;
    ChineseCodePanel imageCode = null;
    
    /**
     * Launch the application
     * 
     * @param args
     */
    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame frame = new MainFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    /**
     * Create the frame
     */
    public MainFrame() {
        super();
        setResizable(false);
        setTitle("中文验证码");
        setBounds(100, 100, 426, 210);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        imageCode = new ChineseCodePanel();// 创建类的实例
        imageCode.setBounds(170, 85, 106, 35);// 设置位置
        getContentPane().add(imageCode); // 添加验证码
        
        final JPanel panel = new JPanel();
        panel.setLayout(null);
        getContentPane().add(panel, BorderLayout.CENTER);
        
        final JButton button = new JButton();
        button.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (imageCode != null) {
                    imageCode.draw(); // 调用方法生成验证码
                }
            }
        });
        button.setText("换一张");
        button.setBounds(301, 90, 94, 28);
        panel.add(button);
        
        final JLabel label = new JLabel();
        label.setText("用户名:");
        label.setBounds(29, 25, 66, 18);
        panel.add(label);
        
        final JLabel label_1 = new JLabel();
        label_1.setText("密   码:");
        label_1.setBounds(29, 59, 66, 18);
        panel.add(label_1);
        
        nameText = new JTextField();
        nameText.setBounds(85, 23, 310, 22);
        panel.add(nameText);
        
        pwdText = new JPasswordField();
        pwdText.setBounds(85, 57, 310, 22);
        panel.add(pwdText);
        
        final JLabel label_1_1 = new JLabel();
        label_1_1.setText("验证码:");
        label_1_1.setBounds(29, 95, 66, 18);
        panel.add(label_1_1);
        
        codeText = new JTextField();
        codeText.setBounds(85, 93, 77, 22);
        panel.add(codeText);
        
        final JButton button_1 = new JButton();
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                String username = nameText.getText();// 从文本框中获取用户名
                String password = new String(pwdText.getPassword());// 从密码框中获取密码
                String code = codeText.getText();// 获得输入的验证码
                String info = "";// 用户登录信息
                // 判断用户名是否为null或空的字符串
                if (username == null || username.isEmpty()) {
                    info = "用户名为空!";
                }
                // 判断密码是否为null或空的字符串
                else if (password == null || password.isEmpty()) {
                    info = "密码为空!";
                }
                // 判断验证码是否为null或空的字符串
                else if (code == null || code.isEmpty()) {
                    info = "验证码为空!";
                }
                // 判断 验证码是否正确
                else if (!code.equals(imageCode.getNum())) {
                    info = "验证码错误!";
                }
                // 如果用户名与密码均为"kuaile",则登录成功
                else if (username.equals("kuaile") && password.equals("kuaile")) {
                    info = "恭喜,登录成功";
                } else {
                    info = "用户名或密码错误!";
                }
                JOptionPane.showMessageDialog(null, info);// 通过对话框弹出用户登录信息
            }
        });
        button_1.setText("登  录");
        button_1.setBounds(42, 134, 106, 28);
        panel.add(button_1);
        
        final JButton button_1_1 = new JButton();
        button_1_1.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                nameText.setText("");// 清除用户名文本框内容
                pwdText.setText("");// 清除密码文本框内容
                codeText.setText("");// 清除验证码文本框内容
            }
        });
        button_1_1.setText("重  置");
        button_1_1.setBounds(191, 134, 106, 28);
        panel.add(button_1_1);
    }
    
}

ChineseCodePanel类实现了验证码设计产生的内部逻辑

package com.application

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.swing.JPanel;

/**
 * 验证码面板
 * 
 *
 */
public class ChineseCodePanel extends JPanel {
    private static final long serialVersionUID = -3124698225447711692L;
    public static final int WIDTH = 120;// 宽度
    public static final int HEIGHT = 35;// 高度
    private String num = "";// 验证码
    Random random = new Random();// 实例化Random
    
    public ChineseCodePanel() {
        this.setVisible(true);// 显示面板
        setLayout(null);// 空布局
    }
    public void paint(Graphics g) {
        String hanZi = "我有一只小毛驴我从来都不骑今天我去上学校我真的很开心";// 定义验证码使用的汉字
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);// 实例化BufferedImage
        Graphics gs = image.getGraphics(); // 获取Graphics类的对象
        if (!num.isEmpty()) {
            num = "";// 清空验证码
        }
        Font font = new Font("黑体", Font.BOLD, 20); // 通过Font构造字体
        gs.setFont(font);// 设置字体
        gs.fillRect(0, 0, WIDTH, HEIGHT);// 填充一个矩形
        // 输出随机的验证文字
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(hanZi.length());// 随机获得汉字的索引值
            String ctmp  = hanZi.substring(index,index+1);// 获得指定索引处的一个汉字
            num += ctmp;// 更新验证码
            Color color = new Color(20 + random.nextInt(120), 20 + random
                    .nextInt(120), 20 + random.nextInt(120));// 生成随机颜色
            gs.setColor(color); // 设置颜色
            Graphics2D gs2d = (Graphics2D) gs;// 将文字旋转指定角度
            AffineTransform trans = new AffineTransform();// 实例化AffineTransform
            trans.rotate(random.nextInt(45) * 3.14 / 180, 22 * i + 8, 7);
            float scaleSize = random.nextFloat() + 0.8f;// 缩放文字
            if (scaleSize > 1f)
                scaleSize = 1f;// 如果scaleSize大于1,则等于1
            trans.scale(scaleSize, scaleSize); // 进行缩放
            gs2d.setTransform(trans);// 设置AffineTransform对象
            gs.drawString(ctmp, WIDTH / 6 * i + 28, HEIGHT / 2);// 画出验证码
        }
        g.drawImage(image, 0, 0, null);// 在面板中画出验证码
    }
    
    // 生成验证码的方法
    public void draw() {
        repaint();// 调用paint()方法
    }
    
    public String getNum() {
        return num;// 返回验证码
    }
}

猜你喜欢

转载自blog.csdn.net/Ibelievesunshine/article/details/84799310