userlogin.java

来自「采用java+sql实现图书管理系统」· Java 代码 · 共 92 行

JAVA
92
字号
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;

public class UserLogin//用户登陆
    extends JFrame
    implements ActionListener {
  DataBaseManager db = new DataBaseManager();
  MainFrame mainFrame;
  JPanel panel1, panel2;
  JLabel userLabel, passwordLabel;
  JTextField userTextField;
  JPasswordField passwordTextField;
  JButton yesBtn, cancelBtn;
  Container c;
  ResultSet rs;
  public UserLogin(MainFrame mainFrame) {
    super("用户登录");
    this.mainFrame = mainFrame;
    userLabel = new JLabel("用户名", JLabel.CENTER);// “用户名”标签
    passwordLabel = new JLabel("密码", JLabel.CENTER);
    userTextField = new JTextField(10);// 用户名输入框
    passwordTextField = new JPasswordField(10);
    yesBtn = new JButton("确定");// “确定”按钮
    cancelBtn = new JButton("取消");
    yesBtn.addActionListener(this);// 为“确定”按钮增加事件监听者
    cancelBtn.addActionListener(this);
    panel1 = new JPanel();
    panel1.setLayout(new GridLayout(2, 2));//2行2列
    panel2 = new JPanel();
    c = getContentPane();
    c.setLayout(new BorderLayout());
    panel1.add(userLabel);
    panel1.add(userTextField);
    panel1.add(passwordLabel);
    panel1.add(passwordTextField);
    c.add(panel1, BorderLayout.CENTER);
    panel2.add(yesBtn);
    panel2.add(cancelBtn);
    c.add(panel2, BorderLayout.SOUTH);
    setSize(300, 300);// 设置窗口大小
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == cancelBtn) {// 单击“取消”按钮后执行的动作
      //mainFrame.setEnable("else");
      this.dispose();
    }
    else {
      char[] password = passwordTextField.getPassword();
      String passwordSTR = new String(password);// 将用户输入的密码由字符数组转换成字符串
      if (userTextField.getText().trim().equals("")) {
        JOptionPane.showMessageDialog(null, "用户名不可为空!");
        return;
      }
      if (passwordSTR.equals("")) {
        JOptionPane.showMessageDialog(null, "密码不可为空!");
        return;
      }
      String strSQL;//连接到数据库的user表,提取用户名和密码
      strSQL = "select * from userTable where UserName='" +
          userTextField.getText().trim() + "'and Password='" +
          passwordSTR + "'";
      rs = db.getResult(strSQL);
      boolean isExist = false;
      try {
        isExist = rs.first();//返回结果
      }
      catch (SQLException sqle) {
        System.out.println(sqle.toString());
      }
      if (!isExist) {
        JOptionPane.showMessageDialog(null, "用户名不存在或者密码不正确!");
        //mainFrame.setEnable("else");
      }
      else {
        try {
          rs.first();//返回的第一条数据
          mainFrame.setEnable(rs.getString("power").trim());//获取该用户权限
          db.closeConnection();
          this.dispose();
        }
        catch (SQLException sqle2) {
          System.out.println(sqle2.toString());
        }
      }

    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?