编写java工具包,用来验证字符串格式和获取登录注册验证码。然后再编写注册窗口,实现注册验证功能。
一、编写工具包
1.编写字符串验证类
考虑到进行字符串验证时,用户会根据不同需求从而需要不同的验证方法,在编写工具包时,尽可能的去满足用户需求。
验证字符串,验证类的自定义规则会提供给用户几种自由选择(包括字符串长度选择、字符串首字符选择、字符串组成选择)。在用户需要验证码字符串时,除了可以进行自定义规则以外,工具包还提供了几种默认规则给用户,规则作为静态的常量作为用户的可选项。在自定义模式中,用户可以使用默认规则,也可以通过函数去修改规则。
用户在进行字符串验证时,除了以上方法以外,还可以直接调用验证类中的静态方法直接通过正则表达式去进行验证,工具包也提供了几种常用的正则表达式验证。
具体代码如下:
package com.register.util;
import java.util.ArrayList;
import java.util.List;
/**
* @author jay
* @category 字符串验证
* <h1>根据规定验证字符串时候规范</h1>
* */
public class StringUtil {
//正则表达式
/**
* @apiNote 用户名验证4到16位(字母,数字,下划线,减号)
* */
public static final int REGULAREXPRESSION_1 = 1;
/**
* @apiNote 密码验证,最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符
* */
public static final int REGULAREXPRESSION_2 = 2;
/**
* @apiNote QQ号验证,5至11位
* */
public static final int REGULAREXPRESSION_3 = 3;
/**
* @apiNote 微信号验证,6至20位,以字母开头,字母,数字,减号,下划线
* */
public static final int REGULAREXPRESSION_4 = 4;
//字符串验证四种规范格式
/**
* @apiNote 自定义格式,默认长度为6-12位,由数字和字母组成的字符串格式
* */
public static final int PATTERN_0 = 0;//自定义格式
/**
* @apiNote 长度为6-12,由字母+数字+特殊字符组成("."),首字符以数字开头的字符串格式
* */
public static final int PATTERN_1 = 1;//格式1
/**
* @apiNote 长度为8-16,由字母+数字+特殊字符组成(".","+")的字符串格式
* */
public static final int PATTERN_2 = 2;//格式2
/**
* @apiNote 长度为4-8,由字母+数字,以大写字母开头的字符串格式
* */
public static final int PATTERN_3 = 3;//格式3
//字符串开头格式(1.数字 2.字母 3.大写字母 4.小写字母 5.无特殊规定)
/**
* @apiNote 字符串以数字开头
* */
public static final int BEGIN_1 = 1;
/**
* @apiNote 字符串以字母开头
* */
public static final int BEGIN_2 = 2;
/**
* @apiNote 字符串以大写字母开头
* */
public static final int BEGIN_3 = 3;
/**
* @apiNote 字符串以小写字母开头
* */
public static final int BEGIN_4 = 4;
/**
* @apiNote 字符串开头无特殊规定
* */
public static final int BEGIN_5 = 5;
//字符串组合格式(1.纯数字 2. 纯字母 3.字母+数字 4.字母+数字+特殊字符)
/**
* @apiNote 字符串以纯数字组成
* */
public static final int GROUP_1 = 1;
/**
* @apiNote 字符串以纯字母组成
* */
public static final int GROUP_2 = 2;
/**
* @apiNote 字符串以字母+数字组成
* */
public static final int GROUP_3 = 3;
/**
* @apiNote 字符串以字母+数字+特殊字符组成
* */
public static final int GROUP_4 = 4;
private int pattern;//当前字符串规范格式选择
private int begin;//字符串开头格式(1.数字 2.字母 3.大写字母 4.小写字母 5.无特殊规定)
private int group;//字符串组合格式(1.纯数字 2. 纯字母 3.字母+数字 4.字母+数字+特殊字符)
private List<Character> chList;//字符串中所允许的特殊字符
private String str;//需要验证的字符串
private int length;//字符串字符串规范长度
private int minLen;//字符串最短长度
private int digitCount = 0;//当前字符串数字个数
private int letterCount = 0;//当前字符串字母个数
private int definedCount = 0;//当前字符串特殊字符个数
/**
* @param str 需要验证的字符串
* @param pattern 验证字符串的规范
* */
public StringUtil(String str,int pattern) {
this.str = str;
this.pattern = pattern;
if(pattern >= 1 && pattern <= 3) {
chList = new ArrayList<Character>();
initPattern();
}else {
defaultPattern();
}
}
/**
* @param str 需要验证的字符串
* @apiNote 默认使用格式1进行验证(长度为6-12,由字母+数字+特殊字符组成("."),首字符以数字开头的字符串格式)
* */
public StringUtil(String str) {
this.str = str;
this.pattern = 1;
if(pattern >= 1 && pattern <= 3) {
chList = new ArrayList<Character>();
initPattern();
}else {
defaultPattern();
}
}
/*
* 当前规范为自定义模式时
* 使用默认信息初始化字符串限定信息
* 默认允许特殊字符‘.’
* */
private void defaultPattern() {
this.length = 12;//限定字符串长度为12
this.minLen = 6;
this.begin = 5;
this.group = 3;
this.chList = new ArrayList<Character>();
chList.add('.');
}
/*
* 根据当前规范格式初始化字符串限定信息
* */
private void initPattern() {
if(this.pattern == 1) {//格式一
this.length = 12;//限定字符串长度为12
this.minLen = 6;
this.chList.add('.');//允许字符串存在特殊字符‘.’
this.begin = 1;//字符串由数字开头
this.group = 4;
}else if(this.pattern == 2) {
this.length = 16;//限定字符串长度为16
this.minLen = 8;
this.chList.add('.');
this.chList.add('+');//允许字符串存在特殊字符‘.’和‘+’
this.begin = 5;
this.group = 4;
}else if(this.pattern == 3) {
this.length = 8;//限定字符串长度为8
this.minLen = 4;
this.begin = 3;//字符串由大写字母
this.group = 3;
}
}
/**
* @param length 限定字符串的长度
* @apiNote 设置自定义格式的参数,有且仅当pattern等于5(自定义格式)的时候,设置生效
* */
public void defined(int minLen,int length) {
if(this.pattern == 0) {
this.length = length;
this.minLen = minLen;
this.begin = 5;
this.group = 3;
}
}
/**
* @param length 限定字符串的长度
* @param begin 规定首字符格式
* @apiNote 设置自定义格式的参数,有且仅当pattern等于5(自定义格式)的时候,设置生效
* */
public void defined(int minLen,int length,int begin) {
if(this.pattern == 0) {
this.length = length;
this.minLen = minLen;
this.begin = begin;
this.group = 3;
}
}
/**
* @param length 限定字符串的长度
* @param begin 规定首字符的格式
* @param group 规定字符串组合格式
* @param chList 设置允许的特殊字符
* @apiNote 设置自定义格式的参数,有且仅当pattern等于5(自定义格式)的时候,设置生效
* */
public void defined(int minLen,int length,int begin,int group,List<Character> chList) {
if(this.pattern == 0) {
this.length = length;
this.minLen = minLen;
this.begin = begin;
this.group = group;
if (chList != null && chList.size() > 0) {
this.chList = chList;
}
}
}
/**
* @param ch 一个特殊字符
* @apiNote 添加自定义格式中的特殊字符
* @apiNote 设置自定义格式的参数,有且仅当pattern等于5(自定义格式)的时候,设置生效
* */
public void addCharacter(char ch) {
if(this.pattern == 0) {
this.chList.add(ch);
}
}
/**
* @param chList 一个特殊字符列表
* @apiNote 添加自定义格式中的特殊字符
* @apiNote 设置自定义格式的参数,有且仅当pattern等于5(自定义格式)的时候,设置生效
* */
public void addCharacter(List<Character> chList) {
if(this.pattern == 0) {
this.chList.addAll(chList);
}
}
/**
* @author jay
* @return 返回当前对象是否符合当前格式规定,符合格式返回true,不符合返回false
*
* */
public boolean isNormalize () {
if(str.length() > this.length || str.length() < this.minLen) return false;//当所验证字符串长度大于规定字符串长度,返回false
if(str.indexOf(' ') != -1) return false;//如果字符串存在空格。返回false
//判断首字符是否规范
if(begin != 5){
//获取字符串首位字符
char ch = str.charAt(0);
if(begin == 1) {//判断首字符是否为数字
if(!Character.isDigit(ch)) {
return false;
}
}else if(begin == 2) {//首字符是否为字母
if(!Character.isLetter(ch)) {
return false;
}
}else if(begin == 3) {//首字符是否为大写字母
if(!Character.isUpperCase(ch)) {
return false;
}
}else if(begin == 4) {//首字符是否为小写字母
if(!Character.isLowerCase(ch)) {
return false;
}
}
}
//统计每种字符个数
statistics();
if(group == 1) {
if(digitCount == length && letterCount == 0 && definedCount == 0) {
return true;
}else return false;
}else if(group == 2) {
if(digitCount == 0 && letterCount == length && definedCount == 0) {
return true;
}else return false;
}else if(group == 3) {
if(digitCount > 0 && letterCount > 0 && digitCount + letterCount == str.length() && definedCount == 0) {
return true;
}else return false;
}else if(group == 4) {
if(digitCount > 0 && letterCount > 0 && definedCount > 0 && definedCount+ digitCount + letterCount == str.length() ) {
return true;
}else return false;
}
return true;
}
/*
* 统计每种字符在字符串中的出现次数
* */
private void statistics() {
for (int i = 0; i < str.length(); i++) {
//获取字符
char ch = str.charAt(i);
//统计字符所属类
if(Character.isLetter(ch)){
this.letterCount++;
}else if(Character.isDigit(ch)) {
this.digitCount++;
}else{
if(chList != null && chList.size() > 0) {
for (Character character : chList) {
if(ch == character) {
this.definedCount++;
break;
}
}
}
}
}
}
//使用正则表达式进行验证
/**
* @param str 需要验证的字符串
* @param model 正则表达式模式
* @return 符合格式返回true,不符合返回false
* @apiNote 使用正则表达式进行验证,默认4到16位(字母,数字,下划线,减号)
* */
public static boolean validate(String str,int model) {
String validateStr = "[a-zA-Z0-9_-]{4,16}"; //默认格式
if(model == 1) {
}else if(model == 2) {
validateStr = ".*(?=.{6,})(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*?.]).*";
}else if(model == 3) {
validateStr = "[1-9][0-9]{4,10}";
}else if(model == 4) {
validateStr = "[a-zA-Z]([-_a-zA-Z0-9]{5,19})+";
}
if(!str.matches(validateStr)) {
return false;
}
return true;
}
/**
* @param str 需要判断的字符串
* @return 如果字符串为空或者字符串为空字符串则返回false,否则返回true
* */
public static boolean isNull(String str) {
str = str.trim();//去除两端空格
if(str != null && !str.equals("")) {
return true;
}else {
return false;
}
}
}
2.邮箱验证类
邮箱验证包括两种方法,一种通过构造函数传入需要验证的邮箱,并调用验证方法,一种则直接通过静态方法使用正则表达式进行验证。
代码如下:
package com.register.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 验证邮箱格式的类
* 可以通过普通验证和正则表达式进行验证
* */
public class EmailUtil {
private static final String EMALI_LIMIT_1 = "@";
private static final String EMALI_LIMIT_2 = "[.]";
private String email;//邮箱
/**
* @param emali 需要验证的邮箱
* @apiNote 邮箱验证的构造函数
* */
public EmailUtil(String email) {
this.email = email;
}
/**
* @return 返回邮箱格式是否正确,正确为true,格式错误为false
*
* */
public boolean isNormalize() {
if(!find(email,'@')) return false;//如果存在多个“@”则返回false
if(!find(email,'.')) return false;//如果存在多个“.”则返回false
String[] arr1 = email.split(EMALI_LIMIT_1);
if(arr1[0].indexOf(".") != -1) {//如果“.”在“@”前面,则返回false
return false;
}
if(arr1[0] == null || arr1[0].length() < 1) {//如果邮箱“@”前字符串长度小于1则返回false
return false;
}
String[] arr2 = arr1[1].split(EMALI_LIMIT_2);
String str1 = arr1[0];
String str2 = arr2[0];
String str3 = arr2[1];
if(str2 == null || str2.length() < 1) return false;
if(str3 == null || str3.length() > 4 || str3.length() < 2) return false;//如果‘.’后面的字符串长度不为2-4区间,则返回false
if(isNormalize2(str1) && isNormalize2(str2) && isNormalize2(str3)) {//验证字符串
return true;
}else {
return false;
}
}
private boolean find(String str,char ch) {
int account = 0;
int index = str.indexOf(ch);
if(index == -1) return false;//如果不存在ch,则返回false
while(true) {
account++;
index = str.indexOf(ch,index + 1);
if(index == -1) break;
if(account > 1) {//如果存在多个@,则返回false
return false;
}
}
return true;
}
/*
* 验证字符串中的字符是否为字母或者数字
*
* */
private boolean isNormalize2(String str) {
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(ch >= 'a' && ch <= 'z') {
continue;
}else if(ch >= 'A' && ch <= 'Z') {
continue;
}else if(ch >= '0' && ch <= '9') {
continue;
}else {
return false;
}
}
return true;
}
/**
* @param emali 需要验证的邮箱
* @return 返回邮箱格式是否正确,正确为true,错误为false
* */
public static boolean validate(String emali) {
String str = "([A-Za-z0-9_\\-\\.])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]{2,4})";
if(!emali.matches(str)) {
return false;
}
return true;
}
}
3.验证码类
用户获取验证码图片时,会根据不同的需求而有所变化。为了尽可能满足用户需求,验证码类实现了验证码多属性可自定义(包括长、宽、验证码字符个数、验证码遮挡线条数等)。
具体代码如下:
package com.register.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.Random;
public class CodeUtil {
private int height;//验证码图片高度
private int width;//验证码图片宽度
private int num;//验证码上的字符个数
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getL_num() {
return l_num;
}
public void setL_num(int l_num) {
this.l_num = l_num;
}
private int l_num;//遮挡线条个数
private BufferedImage bfImage;
private Graphics g;//画笔
Random rand = new Random();
private char[] arrs;
/**
* @param height 验证码的高度
* @param width 验证码的宽度
* @param num 验证码所含随机字符数
* @apiNote 默认遮挡线条为10条
*
* */
public CodeUtil(int height,int width,int num,int l_num) {
this.height = height;
this.width = width;
this.num = num;
this.l_num = l_num;
//初始化验证码信息
initImage();
}
/**
* @param height 验证码的高度
* @param width 验证码的宽度
* @param num 验证码所含随机字符数
* @apiNote 默认遮挡线条为10条
*
* */
public CodeUtil(int height,int width,int num) {
this.height = height;
this.width = width;
this.num = num;
//默认十条
this.l_num = 10;
//初始化验证码信息
initImage();
}
/**
* @param height 验证码的高度
* @param width 验证码的宽度
* @apiNote 默认验证码内容为四个随机字符,且遮挡线条为10
* */
public CodeUtil(int height,int width) {
this.height = height;
this.width = width;
this.num = 4;
//默认十条
this.l_num = 10;
//初始化验证码信息
initImage();
}
/**
*@apiNote 默认验证码高50,宽150,内容有四个随机字符,且遮挡线条为10
*
* */
public CodeUtil() {
this.height = 50;
this.width = 120;
this.num = 4;
//默认十条
this.l_num = 10;
//初始化验证码信息
initImage();
}
/*
*初始化图片信息和画笔,并进行绘画
**/
private void initImage() {
bfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);//创建一个图片
g = bfImage.getGraphics();//获取画笔
draw();//绘画
}
/*
* 绘画
* */
private void draw() {
//定义验证码字符集
String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
//红色、绿色和蓝色值的不透明的 sRGB 颜色,这些值都在 (0 - 255) 的范围内。
int rBack;
int gBack;
int bBack;
//动态生成验证码背景颜色
rBack = rand.nextInt(255);
gBack = rand.nextInt(255);
bBack = rand.nextInt(255);
//绘制图片背景
this.g.setColor(new Color(rBack,gBack,bBack));
this.g.fillRect(0, 0, width, height);
arrs = new char[num];
//获取num个字符
for (int i = 0; i < arrs.length; i++) {
int index = rand.nextInt(str.length());
arrs[i] = str.charAt(index);
}
int r = 0;
int g = 0;
int b = 0;
//绘制线条,作为涂鸦
for (int i = 0; i < this.l_num; i++) {
r = rand.nextInt(255);
g = rand.nextInt(255);
b = rand.nextInt(255);
this.g.setColor(new Color(r,g,b));
this.g.drawLine(rand.nextInt(width), rand.nextInt(height), rand.nextInt(width), rand.nextInt(height));
}
//绘制字符
for (int i = 0; i < arrs.length; i++) {
//动态生成验证码字符颜色
//通过while额循环控制字符颜色不与背景颜色相同
while(true) {
r = rand.nextInt(255);
g = rand.nextInt(255);
b = rand.nextInt(255);
if(r != rBack || g != gBack || b != bBack) {
break;
}
}
//设置画笔颜色
this.g.setColor(new Color(r,g,b));
//设置画笔字体
this.g.setFont(new Font("楷体", Font.BOLD, 25));
//设置字符高度
int h = 25;
if(height > 25) {
h = height / 2 + 10;
}
h = rand.nextInt(20) + h - 10 ;//控制每个字符高度在某个区间内随机生成
int w = i * 25 + 5 * (i + 1);
w = rand.nextInt(10) + w - 5;//控制每个字符宽度在某个区间内随机生成
//绘制字符
this.g.drawString(Character.toString(arrs[i]), w, h);
}
}
/**
* @return 返回验证码内容的字符串
* */
public String getCode() {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arrs.length; i++) {
sb.append(arrs[i]);
}
return sb.toString();
}
/**
* @return 返回已生成的验证码图片
* */
public BufferedImage getImage() {
return bfImage;
}
/**
* @apiNote 刷新验证码
* */
public void update() {
initImage();
}
}
4.打包工具包
当前项目目录结构如下:
开始导出。
鼠标右键单机项目,选择导出。
选择JAR文件,点击下一步。
选择导出文件和路径,点击完成。jar包文件如下:
二、构建jar包路径
1.新建登录项目
复制上一步得到的jar包文件,创建一个新的项目,并在项目下新建一个名为lib的文件,将复制的jar包文件粘贴到lib文件下。如下:
2.构建路径
如图所示,点击添加至构建路径,结果如下:
三、实现注册窗口
1.注册面板
新建包,并在包中创建注册类继承JPanel作为注册的面板,代码如下:
package com.jay.view;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import com.register.util.CodeUtil;
import com.register.util.EmailUtil;
import com.register.util.StringUtil;
public class RegisterJpanel extends JPanel{
private JLabel lblBackground;
private JLabel lbl_UserNameInfo;
private JLabel lbl_PassInfo;
private JLabel lbl_EmailInfo;
private JLabel lbl_CodeInfo;
private JLabel lbl_CodeImage;
private JLabel lbl_Register;
private JLabel lbl_Login;
private JTextField txtUserName;
private JPasswordField txtPassword;
private JTextField txtEmail;
private JTextField txtCode;
private CodeUtil code;
private String codeStr;
private Border border;
private StringUtil strUtil;
public RegisterJpanel() {
//初始化面板信息
init();
//初始化验证码
initImage();
//初始化其他标签组建
initLabel();
//添加输入框
initText();
//初始化注册框背景
initbackground();
//添加按钮监听事件
addListenerEvent();
}
//初始化面板基础信息
private void init() {
this.setBounds(0, 30, 660, 320);
this.setLayout(null);
}
//注册判定
private void register() {
String userName = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
String nCode = txtCode.getText();
lbl_UserNameInfo.setText(null);
lbl_PassInfo.setText(null);
lbl_EmailInfo.setText(null);
lbl_CodeInfo.setText(null);
txtUserName.setBorder(border);
txtPassword.setBorder(border);
txtEmail.setBorder(border);
txtCode.setBorder(border);
//判断是否为空
if(!StringUtil.isNull(userName)) {//如果用户名为空
lbl_UserNameInfo.setText("用户名不能为空");
txtUserName.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.RED));
}
if(!StringUtil.isNull(password)) {//如果密码为空
lbl_PassInfo.setText("密码不能为空");
txtPassword.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
}
if(!StringUtil.isNull(email)) {//如果邮箱为空
lbl_EmailInfo.setText("邮箱不能为空");
txtEmail.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
}
if(!StringUtil.isNull(nCode)) {//如果验证码为空
lbl_CodeInfo.setText("验证码不能为空");
txtCode.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
}
if(!StringUtil.isNull(userName) || !StringUtil.isNull(password) || !StringUtil.isNull(email) || !StringUtil.isNull(nCode) ) {
return;//当输入信息都不为空时进行下一步判断,否则跳出
}
//验证账号
strUtil = new StringUtil(userName, StringUtil.PATTERN_0);//使用自定义格式进行验证码
//设置用户名长度为6-10,以字母开头,由数字、字母、特殊字符且允许使用'_','~'特殊字符
strUtil.defined(6, 10, StringUtil.BEGIN_2, StringUtil.GROUP_4, Arrays.asList('_','~'));
if(!strUtil.isNormalize()) {
lbl_UserNameInfo.setText("用户名格式错误(6-10位,字母开头,由数字、字母、特殊字符('_','~')组成)");
txtUserName.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.RED));
return;
}
//验证码密码
//直接调用静态方法使用正则表达式进行密码验证
//最少6位,包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符
if(!StringUtil.validate(password, StringUtil.REGULAREXPRESSION_2)) {
lbl_PassInfo.setText("密码格式错误(最少6位.包括至少1个大写字母,1个小写字母,1个数字,1个特殊字符)");
txtPassword.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
return;
}
//验证码邮箱
/*
* 方法1:调用实例化EmailUtil对象,并传入需要验证的邮箱,调用isNormalize()进行格式验证
* 方法2:直接调用EmailUtil中的validate()静态方法运用正则表达式进行邮箱格式验证
* */
//方法1
EmailUtil e = new EmailUtil(email);
if(!e.isNormalize()) {
lbl_EmailInfo.setText("邮箱格式错误");
txtEmail.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
return;
}
//方法2
// if(!EmailUtil.validate(email)) {
// lbl_EmailInfo.setText("邮箱格式错误");
// txtEmail.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
// }
//验证验证码
//比较输入的字符串和当前验证码图片中的字符串
if(!nCode.equalsIgnoreCase(codeStr)) {
lbl_CodeInfo.setText("验证码错误");
txtCode.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
return;
}
//注册成功
System.out.println("注册成功!\n注册信息如下:");
//打印注册信息
System.out.println("用户名:\t" + userName +"\n密码:\t" + password + "\n邮箱:\t" + email);
}
private void addListenerEvent() {
//给登录按钮添加鼠标监听事件
this.lbl_Login.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("点击了登录按钮");
}
});
//给注册按钮添加鼠标监听事件
this.lbl_Register.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("点击了注册按钮");
register();
}
});
this.lbl_CodeImage.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
code.update();//更新验证码
codeStr = code.getCode();//更新验证码内容
lbl_CodeImage.setIcon(new ImageIcon(code.getImage()));//更新显示信息
}
});
}
//初始化输入框信息
private void initText() {
//用户名输入框
txtUserName = new JTextField();
txtUserName.setFont(new Font("宋体", Font.BOLD, 12));
txtUserName.setBounds(120, 50, 200, 26);
//密码输入框
txtPassword = new JPasswordField();
txtPassword.setFont(new Font("宋体", Font.BOLD, 12));
txtPassword.setBounds(120, 100, 200, 26);
//邮箱输入框
txtEmail = new JTextField();
txtEmail.setFont(new Font("宋体", Font.BOLD, 12));
txtEmail.setBounds(120, 150, 200, 26);
//验证码输入框
txtCode = new JTextField();
txtCode.setFont(new Font("宋体", Font.BOLD, 12));
txtCode.setBounds(120, 200, 60, 26);
//添加控件
this.add(txtUserName);
this.add(txtPassword);
this.add(txtEmail);
this.add(txtCode);
//记录默认的输入框边框格式
border = txtUserName.getBorder();
}
private void initLabel() {
//初始化用户名标签
JLabel lbl_1 = new JLabel("用户名:");
lbl_1.setIcon(new ImageIcon("images/userName.png"));
lbl_1.setForeground(Color.WHITE);
lbl_1.setFont(new Font("宋体", Font.BOLD, 12));
lbl_1.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_1.setBounds(10, 50, 100, 26);
//初始化用户名提示标签
lbl_UserNameInfo = new JLabel();
lbl_UserNameInfo.setForeground(Color.RED);
lbl_UserNameInfo.setFont(new Font("宋体", Font.BOLD, 12));
lbl_UserNameInfo.setHorizontalAlignment(SwingConstants.LEFT);
lbl_UserNameInfo.setBounds(120, 76, 500, 20);
//初始化密码标签
JLabel lbl_2 = new JLabel("密 码:");
lbl_2.setIcon(new ImageIcon("images/password.png"));
lbl_2.setForeground(Color.WHITE);
lbl_2.setFont(new Font("宋体", Font.BOLD, 12));
lbl_2.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_2.setBounds(10, 100, 100, 26);
//初始化密码提示标签
lbl_PassInfo = new JLabel();
lbl_PassInfo.setForeground(Color.RED);
lbl_PassInfo.setFont(new Font("宋体", Font.BOLD, 12));
lbl_PassInfo.setHorizontalAlignment(SwingConstants.LEFT);
lbl_PassInfo.setBounds(120, 126, 500, 20);
//初始化邮箱标签
JLabel lbl_3 = new JLabel("邮 箱:");
lbl_3.setForeground(Color.WHITE);
lbl_3.setFont(new Font("宋体", Font.BOLD, 12));
lbl_3.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_3.setBounds(10, 150, 100, 26);
//初始化邮箱提示标签
lbl_EmailInfo = new JLabel();
lbl_EmailInfo.setForeground(Color.RED);
lbl_EmailInfo.setFont(new Font("宋体", Font.BOLD, 12));
lbl_EmailInfo.setHorizontalAlignment(SwingConstants.LEFT);
lbl_EmailInfo.setBounds(120, 176, 150, 20);
//初始化验证码标签
JLabel lbl_4 = new JLabel("验证码:");
lbl_4.setForeground(Color.WHITE);
lbl_4.setFont(new Font("宋体", Font.BOLD, 12));
lbl_4.setHorizontalAlignment(SwingConstants.RIGHT);
lbl_4.setBounds(10, 200, 100, 26);
//初始化验证码提示标签
lbl_CodeInfo = new JLabel();
lbl_CodeInfo.setForeground(Color.RED);
lbl_CodeInfo.setFont(new Font("宋体", Font.BOLD, 12));
lbl_CodeInfo.setHorizontalAlignment(SwingConstants.LEFT);
lbl_CodeInfo.setBounds(120, 226,200, 20);
//初始化验证码图片
lbl_CodeImage = new JLabel();
lbl_CodeImage.setIcon(new ImageIcon(code.getImage()));
lbl_CodeImage.setBounds(200, 186, 150, 50);
//登录按钮
lbl_Login = new JLabel();
lbl_Login.setIcon(new ImageIcon("images/logins.png"));
lbl_Login.setBounds(208, 250, 68, 28);
//注册按钮
lbl_Register = new JLabel();
lbl_Register.setIcon(new ImageIcon("images/register.png"));
lbl_Register.setBounds(100, 250, 68, 28);
//向面板添加控件
this.add(lbl_1);
this.add(lbl_2);
this.add(lbl_3);
this.add(lbl_4);
this.add(lbl_UserNameInfo);
this.add(lbl_PassInfo);
this.add(lbl_EmailInfo);
this.add(lbl_CodeInfo);
this.add(lbl_Register);
this.add(lbl_Login);
this.add(lbl_CodeImage);
}
/**
*初始化验证码信息
*/
private void initImage() {
//获取验证码
this.code = new CodeUtil(40,120);
this.codeStr = code.getCode();
}
//初始化注册背景
private void initbackground() {
lblBackground = new JLabel();
lblBackground.setBounds(0, 0, 660, 320);
lblBackground.setIcon(new ImageIcon("images/login.png"));
this.add(lblBackground);
}
}
2.实现启动方法
新建包和类,并创建主方法,在其中创建一个JFrame窗体用作为注册窗口。代码如下:
package com.jay.controller;
import java.awt.Component;
import javax.swing.JFrame;
import com.jay.view.RegisterJpanel;
public class RegisterController {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setBounds(0, 0, 660, 355);
jf.setResizable(false);
jf.setLocationRelativeTo(null);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RegisterJpanel registerJpanel = new RegisterJpanel();
jf.add(registerJpanel);
jf.setVisible(true);
}
}
四、测试
1.输入为空时
2.输入用户名格式错误时
3.输入密码格式错误时
4.输入邮箱错误时
5.输入验证码错误时
6.注册成功时