当前位置:网站首页>GUI user login

GUI user login

2022-06-09 22:39:00 Liangchenxing


GUI The user login

  • User login interface
     Insert picture description here

  • The function realization should utilize JDBC Operating the database

  • Login successful , A message box will pop up to prompt the user - Congratulations , Login successful !

  • Login failed , A message box will pop up to prompt the user - regret , Login failed ! Wrong account or password !

  • Required MVC framework
     Insert picture description here

One , Implement programming

Create databases and tables

(1) Create student database

stay Navicat To create a new query, enter the following statement , Then run create student database .

CREATE DATABASE student CHARSET=‘utf8mb4’;

(2) newly build t_use surface

stay Navicat Create a new query in , Then enter the following statement , Then run create t_user surface .

CREATE TABLE t_user (
id int(11) NOT NULL AUTO_INCREMENT COMMENT ‘ user ID’,
username varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ user name ’,
password varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ User password ’,
telephone varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ contact number ’,
register_time timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT ‘ Registration time ’,
PRIMARY KEY (id) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4;

(3) by t_user Insert three records

stay Navicat Create a new query in , Enter the following three statements , Then run insert record to t_user In the table .

INSERT INTO t_user (username, password, telephone, register_time)
VALUES (‘admin’, ‘12345’, ‘13945456780’, ‘2022-01-01 09:10:34’);

INSERT INTO t_user (username, password, telephone, register_time)
VALUES (‘brown’, ‘11111’, ‘13878789089’, ‘2022-03-12 19:05:44’);

INSERT INTO t_user (username, password, telephone, register_time)
VALUES (‘alice’, ‘22222’, ‘15834345670’, ‘2022-04-04 15:16:24’);

Two 、 Create user entity class

import java.util.Date;
/**
 *  function : User entity class 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 02 Japan 
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String telephone;
    private Date registerTime;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", telephone='" + telephone + '\'' +
                ", registerTime=" + registerTime +
                '}';
    }
}

3、 ... and 、 Add database driver package

1. Create in project root libs Catalog , Add database driver package .

 Insert picture description here

2. here , This jar The package is not yet available for use by the project , It needs to be added to the project as a library .

 Insert picture description here

3. single click Add as Library… A menu item , stay create library No settings are made in the dialog box , Just click OK Button .

 Insert picture description here

4. At this time , The database driver package can be used by the project .

 Insert picture description here

5. see JDBC Important interfaces and classes .

 Insert picture description here

Four 、 Create a database connection management class

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *  function : Database connection management class 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 09 Japan 
 */
public class ConnectionManager {
    //  Database connection properties 
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/student?useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "903213"; //  Change the password of your database 

    /**
     *  Privatized construction method , Reject instantiation 
     */
    private ConnectionManager() {
    }

    /**
     *  Get the database connection static method 
     *
     * @return  Database connection 
     */
    public static Connection getConnection() {
        //  Define database connection 
        Connection conn = null;

        try {
            //  Install database driver 
            Class.forName(DRIVER);
            //  Get database connection 
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            //  Prompt the user that the database connection is successful 
            System.out.println(" Tips : Database connection successful ~");
        } catch (ClassNotFoundException e) {
            System.err.println(" abnormal : Database driver not found !");
        } catch (SQLException e) {
            System.err.println(" abnormal : Database connection failed !");
        }

        //  Back to database connection 
        return conn;
    }

    /**
     *  Close the database connection static method 
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        //  Determine whether the connection is empty 
        if (conn != null) {
            try {
                //  Determine whether the connection is closed 
                if (!conn.isClosed()) {
                    //  Close database connection , Release resources 
                    conn.close();
                    //  Prompt the user 
                    System.out.println(" Tips : Database connection closed ~");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  The main method tests the database connection 
     *
     * @param args
     */
    public static void main(String[] args) {
        //  Get database connection 
        Connection conn = getConnection();
        //  Close database connection 
        closeConnection(conn);
    }
}

5、 ... and 、 Create a user data provider

import d01.a01.User;
import java.util.List;

/**
 *  function : User data access interface 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 02 Japan 
 */
public interface UserDao {
    int insert(User user);
    int delete(int id);
    int update(User user);
    User findById(int id);
    List<User> findAll();
    User login(String username, String password);
}

6、 ... and 、 Create a user data provider implementation class

import d01.a01.User;
import d01.dao.UserDao;
import d01.dbutils.ConnectionManager;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 *  function : User data access interface implementation class 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 09 Japan 
 */
public class UserDaoImpl implements UserDao {
    @Override
    public int insert(User user) {
        return 0;
    }

    @Override
    public int deleteById(int id) {
        return 0;
    }

    @Override
    public int update(User user) {
        return 0;
    }

    @Override
    public int findById(int id) {
        return 0;
    }

    @Override
    public List<User> findAll() {
        //  Define user list 
        List<User> users = new ArrayList<>();

        //  Get database connection 
        Connection conn = ConnectionManager.getConnection();
        //  establish SQL character string 
        String strSQL = "select * from t_user";

        try {
            //  Create statement object 
            Statement stmt = conn.createStatement();
            //  perform SQL Inquire about , Return result set 
            ResultSet rs = stmt.executeQuery(strSQL);
            //  Traversal result set , Build a list of users 
            while (rs.next()) {
                //  Create user objects 
                User user = new User();
                //  Set the user object attribute value with the current record field value 
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }


        //  Return to user list 
        return users;
    }

    @Override
    public User login(String username, String password) {
        //  Define user objects 
        User user = null;
        //  Get database connection 
        Connection conn = ConnectionManager.getConnection();
        //  establish SQL character string 
        String strSQL = "select * from t_user where username = ? and password = ?";
        try {
            //  Create a prepared statement object ( Prepare to provide parameters )
            PreparedStatement pstmt = conn.prepareStatement(strSQL);
            //  Set the value of the placeholder with the parameter value 
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            //  perform SQL Inquire about , Return result set 
            ResultSet rs = pstmt.executeQuery();
            //  Traversal result set , Fill the user object with record values 
            while (rs.next()) {
                //  Create user objects 
                user = new User();
                //  Set the user object attribute value with the current record field value 
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setTelephone(rs.getString("telephone"));
                user.setRegisterTime(rs.getTimestamp("register_time"));
            }
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            ConnectionManager.closeConnection(conn);
        }
        //  Return user object 
        return user;
    }
}

7、 ... and 、 Create a user service class

import d01.a01.User;
import d01.dao.UserDao;
import d01.dao.impl.UserDaoImpl;

import java.util.List;

/**
 *  function : User service class 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 09 Japan 
 */
public class UserService {
    private UserDao userDao;

    public UserService() {
        userDao = new UserDaoImpl();
    }

    public int addUser(User user) {
        return userDao.insert(user);
    }

    public int deleteUser(int id) {
        return userDao.deleteById(id);
    }

    public int updateUser(User user) {
        return userDao.update(user);
    }

    public User findUserById(int id) {
        return userDao.findById(id);
    }

    public List<User> findAllUser() {
        return userDao.findAll();
    }

    public User login(String username, String password) {
        return userDao.login(username, password);
    }
}

8、 ... and 、 Create a user login interface

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;

/**
 *  function : User login window 
 *  author : Liangchenxing 
 *  date :2022 year 06 month 09 Japan 
 */
public class LoginFrame extends JFrame {
    private String username;
    private String password;

    private JLabel lblUsername;
    private JLabel lblPassword;
    private JTextField txtUsername;
    private JPasswordField txtPassword;

    private JButton btnOK;
    private JButton btnCancel;

    private JPanel panel, panel1, panel2, panel3;

    /**
     *  Parametric construction method 
     *
     * @param title
     */
    public LoginFrame(String title) {
        super(title);
        initGUI(); //  Call the initialize GUI method 
    }

    /**
     *  Initialize the GUI method 
     */
    private void initGUI() {
        //  Instantiated component ( Panels and controls )
        panel = (JPanel) getContentPane();
        panel1 = new JPanel();
        panel2 = new JPanel();
        panel3 = new JPanel();

        lblUsername = new JLabel(" user name :");
        lblPassword = new JLabel(" The secret      code :");
        txtUsername = new JTextField(15);
        txtPassword = new JPasswordField(15);
        btnOK = new JButton(" determine [O]");
        btnCancel = new JButton(" Cancel [C]");

        //  Add the control to the three small panels 
        panel1.add(lblUsername);
        panel1.add(txtUsername);
        panel2.add(lblPassword);
        panel2.add(txtPassword);
        panel3.add(btnOK);
        panel3.add(btnCancel);

        //  Set the main panel as a grid layout with three rows and one column 
        panel.setLayout(new GridLayout(3, 1));
        //  Add three small panels to the main panel in turn 
        panel.add(panel1);
        panel.add(panel2);
        panel.add(panel3);

        //  Set button hotkey letters 
        btnOK.setMnemonic(KeyEvent.VK_O);
        btnCancel.setMnemonic(KeyEvent.VK_C);
        //  Set password box echo character 
        txtPassword.setEchoChar('*');

        //  Set window size 
        setSize(250, 200);
        //  Set the window screen to center 
        setLocationRelativeTo(null);
        //  The setup window is not resizable 
        setResizable(false);
        //  The setup window just holds the components 
        pack();
        //  Set window visible 
        setVisible(true);
        //  Set the default window closing operation 
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    public static void main(String[] args) {
        new LoginFrame(" The user login ");
    }
}
  • Run code , give the result as follows .
     Insert picture description here

Nine 、 Realize user login function

  • involve GUI Event handling mechanism of : event 、 Event source 、 Monitor ( Event handling method ).
     Insert picture description here
  • Create event handling methods eventHanding(), And call... In the constructor .
/**                                                                                                                   
 *  Event handling                                                                                                                
 */                                                                                                                   
private void eventsHandling() {                                                                                       
    //  to 【 determine 】 Button register listener                                                                                                    
    btnOK.addActionListener(new ActionListener() {                                                                    
        @Override                                                                                                     
        public void actionPerformed(ActionEvent e) {                                                                  
            //  Get the user name and password entered by the user                                                                                           
            username = txtUsername.getText().trim();                                                                  
            password = new String(txtPassword.getPassword());                                                         
            //  Create a user service object                                                                                                
            UserService userService = new UserService();                                                              
            //  Call the login method of the service object                                                                                             
            User user = userService.login(username, password);                                                        
            //  Judge whether the user login is successful                                                                                              
            if (user != null) {                                                                                       
                //  A message box will pop up to prompt the user                                                                                           
                JOptionPane.showMessageDialog(null, " Congratulations ,[" + username + "] Login successful ~");                                    
                dispose(); //  Close the login window                                                                                   
            } else {                                                                                                  
                //  A message box will pop up to prompt the user                                                                                           
                JOptionPane.showMessageDialog(null, " regret , Wrong user name or password ~");                                                  
                //  Clear both text boxes                                                                                             
                txtUsername.setText("");                                                                              
                txtPassword.setText("");                                                                              
                //  Let the name text box get the focus                                                                                          
                txtUsername.requestFocus();                                                                           
            }                                                                                                         
        }                                                                                                             
    });                                                                                                               
                                                                                                                      
    //  to 【 Cancel 】 Button register listener                                                                                                    
    btnCancel.addActionListener(new ActionListener() {                                                                
        @Override                                                                                                     
        public void actionPerformed(ActionEvent e) {                                                                  
            System.exit(0); //  exit from application program                                                                                  
        }                                                                                                             
    });                                                                                                               
}                                                                                                                     

原网站

版权声明
本文为[Liangchenxing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206092155097433.html