您的位置:首页 > 编程语言 > Java开发

java Swing中随机验证码的实现

2015-06-02 17:46 417 查看
LoginJFrame:(登录界面)

package com.myproject.ui;

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
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;

import com.myproject.bean.User;
import com.myproject.uiutils.ValidCode;
import com.myproject.userdao.UserDAOFactory;

public class LoginJFrame extends JFrame {

private static final long serialVersionUID = 1L;
private JLabel lb_backgroud;// 背景
private JLabel label = new JLabel("目标管理系统");
private JLabel username = new JLabel("用户名:");
private JLabel password = new JLabel("密 码:");
private JLabel validcode = new JLabel("验证码:");
private JPanel jp1 = new JPanel();// 标题面板
private JTextField jtf_user = new JTextField();
private JPasswordField jpf_pwd = new JPasswordField();
private JTextField jtf_code = new JTextField();
private JButton btn_login = new JButton("登录");
private JButton btn_regist = new JButton("注册");
private ValidCode vcode;

public LoginJFrame() {
showUI();
BtnLoginAddActionListener();
setBackgroudImage();
}

/**
* 初始化登录窗体背景
*/
private void setBackgroudImage() {
((JPanel) this.getContentPane()).setOpaque(false);
ImageIcon img = new ImageIcon("images/beijing1.jpg"); // 添加图片
lb_backgroud = new JLabel(img);
this.getLayeredPane().add(lb_backgroud, new Integer(Integer.MIN_VALUE));
lb_backgroud.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
}

private void showUI() {
this.setTitle("南华大学目标管理系统");
this.setSize(450, 350);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);

Container c = this.getContentPane();
c.setLayout(null);

label.setFont(new Font("宋体", 0, 30));
// jp1.setBackground(Color.gray);
jp1.add(label);
jp1.setBounds(100, 30, 250, 45);
jp1.setOpaque(false);
c.add(jp1);

username.setBounds(80, 90, 60, 40);
password.setBounds(80, 140, 60, 40);
validcode.setBounds(80, 190, 60, 40);

jtf_user.setBounds(140, 90, 180, 40);
jtf_user.setOpaque(false);
jpf_pwd.setBounds(140, 140, 180, 40);
jpf_pwd.setOpaque(false);
jtf_code.setBounds(140, 190, 100, 40);

btn_login.setBounds(120, 250, 80, 40);
setJButton(btn_login);
btn_regist.setBounds(220, 250, 80, 40);
setJButton(btn_regist);

c.add(username);
c.add(password);
c.add(validcode);
c.add(jtf_user);
c.add(jpf_pwd);
c.add(jtf_code);
vcode = new ValidCode();
vcode.setBounds(240, 190, 80, 40);
c.add(vcode);
c.add(btn_login);
c.add(btn_regist);

this.setVisible(true);

}

/**
* 为了适应各种不同尺寸大小的窗口都能显示在屏幕中间位置,相当于setLocationRelativeTo(null) private void
* setCenter(){ Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension d =
* toolkit.getScreenSize(); int x = (int)(d.getWidth()-getWidth())/2; int y
* = (int)(d.getHeight()-getHeight())/2; this.setLocation(x, y); }
*/

/**
* 给登录按钮添加监听
*/
public void BtnLoginAddActionListener() {
btn_login.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!isValidCodeRight()) {
JOptionPane.showMessageDialog(LoginJFrame.this, "验证码错误!");
}
if (isValidCodeRight()) {

String userName = jtf_user.getText();
String passWord = String.valueOf(jpf_pwd.getPassword());
User user = new User();
user.setUsername(userName);
user.setPassword(passWord);
Boolean flag = false;
try {
flag = UserDAOFactory.getUserDAOInstance().findLogin(
user);
} catch (Exception e1) {
e1.printStackTrace();
}

// 判断
if (!flag) {
JOptionPane.showMessageDialog(LoginJFrame.this,
"用户名或密码错误,请重输!");
} else {
System.out.println("登录成功!!!");
new MainJFrame().init();
LoginJFrame.this.dispose();
}
}
}
});
}

/**
* 给注册按钮添加监听
*/
public void BtnRegistAddActionListener() {
btn_regist.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {

}
});
}

/**
* 设置按钮风格:透明
*
* @param btn
*/
private void setJButton(JButton btn) {
btn.setBackground(new Color(102, 0, 204));// 紫色
btn.setFont(new Font("Dialog", Font.BOLD, 24));
btn.setOpaque(false);
btn.setBorder(BorderFactory.createEmptyBorder());
}

/**
* 验证码的校验
*
* @return
*/
public boolean isValidCodeRight() {

if (jtf_code == null) {
return false;
}
if (vcode == null) {
return true;
}
if (vcode.getCode().equals(jtf_code.getText())) {
return true;
}
return false;
}

}


ValidCode:随机验证码的实现类
package non.zy.login;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.util.Random;

import javax.swing.JComponent;

public class ValidCode extends JComponent implements MouseListener {

private String code;

private int width, height = 40;

private int codeLength = 4;

private Random random = new Random();

public ValidCode() {
width = this.codeLength * 16 + (this.codeLength - 1) * 10;
setPreferredSize(new Dimension(width, height));
setSize(width, height);
this.addMouseListener(this);
setToolTipText("点击可以更换验证码");
}

public int getCodeLength() {
return codeLength;
}

/*
设置验证码文字的长度
*/
public void setCodeLength(int codeLength) {
if(codeLength < 4) {
this.codeLength = 4;
} else {
this.codeLength = codeLength;
}

}

public String getCode() {
return code;
}

/*
产生随机的颜色
*/
public Color getRandColor(int min, int max) {

if (min > 255)
min = 255;
if (max > 255)
max = 255;
int red = random.nextInt(max - min) + min;
int green = random.nextInt(max - min) + min;
int blue = random.nextInt(max - min) + min;
return new Color(red, green, blue);
}
/*
设置验证码具体的字母是什么
*/
protected String generateCode() {
char[] codes = new char[this.codeLength];
for (int i = 0, len = codes.length; i < len; i++) {
if (random.nextBoolean()) {
codes[i] = (char) (random.nextInt(26) + 65);
} else {
codes[i] = (char) (random.nextInt(26) + 97);
}
}
this.code = new String(codes);
return this.code;
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(this.code == null || this.code.length() != this.codeLength) {
this.code = generateCode();
}
width = this.codeLength * 16 + (this.codeLength - 1) * 10;
super.setSize(width, height);
super.setPreferredSize(new Dimension(width, height));
Font mFont = new Font("Arial", Font.BOLD | Font.ITALIC, 25);
g.setFont(mFont);
//绘制出验证码的背景的矩形轮廓
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getRandColor(200, 250));
g2d.fillRect(0, 0, width, height);
g2d.setColor(getRandColor(180, 200));
g2d.drawRect(0, 0, width - 1, height - 1);
//绘制出验证码背景的线
int i = 0, len = 150;
for (; i < len; i++) {
int x = random.nextInt(width - 1);
int y = random.nextInt(height - 1);
int x1 = random.nextInt(width - 10) + 10;
int y1 = random.nextInt(height - 4) + 4;
g2d.setColor(getRandColor(180, 200));
g2d.drawLine(x, y, x1, y1);
}

/*i = 0; len = 300;
for (; i < len; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
g2d.setColor(getRandColor(150, 180));
g2d.drawRect(x, y, 0, 0);
}*/

//绘制出验证码的具体字母
i = 0; len = this.codeLength;
FontMetrics fm = g2d.getFontMetrics();
int base = (height - fm.getHeight())/2 + fm.getAscent();
for(;i<len;i++) {
int b = random.nextBoolean() ? 1 : -1;
g2d.rotate(random.nextInt(10)*0.01*b);
g2d.setColor(getRandColor(20, 130));
g2d.drawString(code.charAt(i)+"", 16 * i + 10, base);
}
}

//下一个验证码
public void nextCode() {
generateCode();
repaint();
}

@Override
public void mouseClicked(MouseEvent e) {

nextCode();
}

@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub

}
}


界面效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: