当前位置:网站首页>GUI user login
GUI user login
2022-06-09 22:39:00 【Liangchenxing】
List of articles
- GUI The user login
- One , Implement programming
- Two 、 Create user entity class
- 3、 ... and 、 Add database driver package
- 1. Create in project root libs Catalog , Add database driver package .
- 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 .
- 3. single click Add as Library… A menu item , stay create library No settings are made in the dialog box , Just click OK Button .
- 4. At this time , The database driver package can be used by the project .
- 5. see JDBC Important interfaces and classes .
- Four 、 Create a database connection management class
- 5、 ... and 、 Create a user data provider
- 6、 ... and 、 Create a user data provider implementation class
- 7、 ... and 、 Create a user service class
- 8、 ... and 、 Create a user login interface
- Nine 、 Realize user login function
GUI The user login
User login interface

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

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(idint(11) NOT NULL AUTO_INCREMENT COMMENT ‘ user ID’,usernamevarchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ user name ’,passwordvarchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ User password ’,telephonevarchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ‘ contact number ’,register_timetimestamp 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 .

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 .

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

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

5. see JDBC Important interfaces and classes .

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 .

Nine 、 Realize user login function
- involve GUI Event handling mechanism of : event 、 Event source 、 Monitor ( Event handling method ).

- 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
}
});
}
边栏推荐
- C language 0 length array (variable array / flexible array) explanation
- [bearing fault decomposition] realize bearing fault signal decomposition based on ITD, including Matlab source code
- Maximum value and subscript of acquisition matrix of C language test question 168
- June training (day 09) - two point search
- Systematic goal - Fitness collection
- YUV格式与RGB格式
- 【刷题篇】最长递增子序列
- YUV format and RGB format
- 數據庫優化方面的經驗
- [image denoising] image denoising based on Gaussian, mean, median and bilateral filtering, including Matlab source code
猜你喜欢

房贷利率下调 现在是买房的时机吗?

lua学习笔记(4)-- 搭建mobdebug 远程开发环境

【报表工具的第二次革命】基于SPL语言优化报表结构、提升报表运算性能

如何实现高效的IM即时通讯长连接自适应心跳保活机制

C语言试题164之求定积分

Gamefi's new departure, aquanee will log in to gate and bitmart on June 9

设计备忘录解矩阵链(动态规划法)的一些思考

Intelligent prevention and control of safety production risk at construction site in flood season

10 common high-frequency business scenarios that trigger IO bottlenecks

15省份发布2021年平均工资,这些行业有“钱途”
随机推荐
经典面试题:如何快速求解根号2?
All inherited features
在 4GB 物理內存的機器上,申請 8G 內存會怎麼樣?
基于JSP实现网上招聘系统
Digital supervision of construction sites and the wisdom of scientific warfare
Veracrypt create file type encrypted volume
【图像重建】基于正则化的图像超分辨重建附matlab代码
Systematic goal - Fitness collection
At present, I am 28 years old, and I have successfully won the 15K salary since I started to wander to the north in 20 years and started to test the entry software
Début de la production de sécurité et prévention et contrôle des épidémies
Expérience de l'optimisation des bases de données
How to use sqlplus to remotely connect ASM instances
Find My产品|新款TWS耳机支持Find My功能,苹果Find My在第三方厂家应用更广泛
Common SQL statements
从小开始勤奋
After the naked resignation in the post epidemic era, the interview with the software test engineer was rejected. Write down some insights and interview experiences
M-arch (yateli M4) [at-start-f425 evaluation] No.05 flash
Aquanee will land in gate and bitmart in the near future, providing a good opportunity for low-level layout
C语言试题163之计算某一天是对应年的第几天,这一年一共多少天;计算两个日期之间相隔的天数。两个日期由键盘输入。
华为设备配置Hub and Spoke