1. 程式人生 > >Java 圖片驗證碼的實現和模擬簡單的登入

Java 圖片驗證碼的實現和模擬簡單的登入

 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;// 返回驗證碼
    }
}