package com.itheima;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class tologin {
public static void main(String[] args) {
JFrame jf=new JFrame();
jf.setTitle("用户登录");
jf.setSize(400,300);
jf.setDefaultCloseOperation(3);
jf.setLocationRelativeTo(null);
jf.setAlwaysOnTop(true);
jf.setLayout(null); //取消窗体的默认布局
//显示用户名文本
JLabel usernameLabel=new JLabel("用户名");
usernameLabel.setBounds(50,50,50,20);
jf.add(usernameLabel);
//用户名输入框
JTextField usernameField = new JTextField();
usernameField.setBounds(150,50,180,20);
jf.add(usernameField);
//显示密码文本
JLabel passwordLabel=new JLabel("密码");
passwordLabel.setBounds(50,100,50,20);
jf.add(passwordLabel);
JPasswordField passwordField = new JPasswordField(); //密码输入框用JPasswordField 加密显示
passwordField.setBounds(150,100,180,20);
jf.add(passwordField);
//登录按钮
JButton LoginButton=new JButton("登录");
LoginButton.setBounds(50,200,280,20);
jf.add(LoginButton);
//已知的用户名和密码
String name ="itheima";
String pwd = "123456";
//给登陆按钮添加一个事件
LoginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//获取用户输入的用户名和密码
String username = usernameField.getText();//获取输入框输入内容
String password = passwordField.getText();
//先判断输入的用户名和密码是否符合要求
//用户名和密码的长度都是6-12位
if (username.length()<6 || username.length()>12){
// System.out.println("用户名的长度是6-12位,请重新输入");
JOptionPane.showMessageDialog(jf,"用户名的长度是6-12位,请重新输入");//窗口弹出文本提示
usernameField.setText("");//清空输入框内容
}
if (password.length()<6 || password.length()>12){
// System.out.println("密码的长度是6-12位,请重新输入");
JOptionPane.showMessageDialog(jf,"密码的长度是6-12位,请重新输入");
passwordField.setText("");
}
//在判断用户登录是否成功
if (username.equals(name)&&password.equals(pwd)){
// System.out.println("登录成功");
JOptionPane.showMessageDialog(jf,"登陆成功");
usernameField.setText("");
passwordField.setText("");
}else{
// System.out.println("用户名或密码有误");
JOptionPane.showMessageDialog(jf,"用户名或密码有误");
usernameField.setText("");
passwordField.setText("");
}
}
});
//添加按钮到窗体中
jf.setVisible(true);
}
}