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

来源:互联网 发布:mac的airplay在哪里 编辑:程序博客网 时间:2024/05/01 19:49

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() {@Overridepublic 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();}}

程序截图:

登录成功截图:

登录失败截图:

1 0
原创粉丝点击