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

Java Swing界面编程(23)---事件处理:编写用户验证登录用例

2014-05-30 14:21 716 查看
LoginCheck:

package com.beyole.util;

class LoginCheck {//编写登录验证类
private String userName;//用户名
private String password;//密码
public LoginCheck(String userName,String password)//复写构造方法
{
this.userName=userName;//为用户名赋值
this.password=password;//为密码赋值
}
public boolean validate()//设置验证方法
{
if("beyole".equals(userName)&&"123456".equals(password))
{
return true;//登录成功
}else {
return false;//登录失败
}
}
}


LoginActionEventDemo:

package com.beyole.util;

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

class ActionHandle {
private JFrame frame = new JFrame("Crystal");// 声明一个 窗体对象
private JButton submit = new JButton("登录");// 声明一个按钮
private JButton reset = new JButton("重置");// 声明一个按钮
private JLabel nameLabel = new JLabel("用户名:");// 声明一个标签
private JLabel passLabel = new JLabel("密     码:");// 声明一个标签
private JLabel infoLabel = new JLabel("用户登录系统");// 声明一个标签
private JTextField nameText = new JTextField();// 定义一个文本域
private JPasswordField passText = new JPasswordField();// 定义一个文本域

public ActionHandle() {
Font font = new Font("Serief", Font.BOLD + Font.ITALIC, 12);// 定义显示的字体
infoLabel.setFont(font);// 设置标签显示的字体
submit.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == submit)// 判断触发源是否为提交按钮
{
String userName = nameText.getText();// 得到输入的用户名
String password = new String(passText.getPassword());// 得到输入的密码,此时通过getPassword()方法返回的是字符数组
LoginCheck loginCheck = new LoginCheck(userName, password);
if (loginCheck.validate()) {
infoLabel.setText("登录成功,欢迎光临");
} else {
infoLabel.setText("登录失败,错误的用户名或密码");
}
}
if (arg0.getSource() == reset)// 判断触发源是否为重置按钮
{
nameText.setText("");// 清空文本框内容
passText.setText("");// 清空密码框内容
infoLabel.setText("用户登录系统");// 恢复标签提示设置
}
}

});
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent arg0) {
System.exit(1);
}
});
frame.setLayout(null);// 设置绝对定位
nameLabel.setBounds(5, 5, 60, 20);
passLabel.setBounds(5, 30, 60, 20);
infoLabel.setBounds(5, 65, 220, 30);
nameText.setBounds(65, 5, 100, 20);
passText.setBounds(65, 30, 100, 20);
submit.setBounds(165, 5, 60, 20);
reset.setBounds(165, 30, 60, 20);
frame.add(infoLabel);
frame.add(nameLabel);
frame.add(nameText);
frame.add(passLabel);
frame.add(passText);
frame.add(reset);
frame.add(submit);
frame.setSize(280, 130);
frame.setVisible(true);
}
}

public class LoginActionEventDemo {
public static void main(String[] args) {
new ActionHandle();
}
}


程序截图:


登录成功截图:


登录失败截图:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐