public class LoginIn { private String name; private String password; public LoginIn(String name,String password){ this.name = name; this.password = password; } public boolean checkOut() { if (("1" .equals(name)) && ("123456".equals(password))){ return true; } else { return false; } } }
package Practice.demo21AWT; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class ActionHandle { private JFrame frame = new JFrame("用户登录系统"); private JButton login = new JButton("登录"); private JButton reset = new JButton("重置"); private JLabel lab = new JLabel("用户登录系统"); private JLabel nameLab = new JLabel("用户名:"); private JLabel passwordLab = new JLabel("密 码:"); private JTextField nameText = new JTextField(); private JPasswordField passwordText = new JPasswordField(); public ActionHandle() { nameLab.setBounds(5,5,60,20); passwordLab.setBounds(5,40,60,20); nameText.setBounds(65,5,220,30); passwordText.setBounds(65,40,220,30); login.setBounds(70,100,60,20); reset.setBounds(170,100,60,20); lab.setBounds(75,150,50,40); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e){ System.out.println("窗口关闭"); } }); login.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == login){ String name = nameText.getText(); String password = new String(passwordText.getPassword()); LoginIn log = new LoginIn(name, password); if (log.checkOut() == true){ lab.setText("登陆成功!"); } else { lab.setText("登录失败!请检查用户名或密码"); } } } }); reset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == reset){ nameText.setText(""); passwordText.setText(""); lab.setText("用户登录系统"); } } }); frame.add(nameLab); frame.add(passwordLab); frame.add(nameText); frame.add(passwordText); frame.add(login); frame.add(reset); frame.add(lab); frame.setSize(350,200); frame.setLocation(500,300); frame.setVisible(true); } }
public class MyActionEventDemo01 { public static void main(String[] args) { new ActionHandle(); } }
测试结果如下:
输入错误用户名或密码时
点击重置按钮会返回开始时界面
输入正确的用户名和密码时,显示登录成功