Java implements a simple login and registration interface based on Swing and JDBC

catalogue

1, Demand analysis

2, Preparatory work

1. Prepare the development environment

2. Prepare the database

3. Prepare for outsourcing

3, Specific steps

1. Open IDEA and create an empty project

 2. After completion, import a new module

3. Import the outsourcing jar package to be used by JDBC.

4, Code implementation

1. Interface class

1.1 login interface

1.2 registration interface

1.3 prompt window

 2. Connection class

2.1 login connection

2.2 registered connection class

3. Testing

5, Final effect display

6, Summary

 

1, Demand analysis

Considering such a requirement, the verification process of login and registration is required. Secondly, we need a graphical interface and prompt whether the login is successful or whether the registration can be successful.

2, Preparatory work

1. Prepare the development environment

Here, I recommend using IDEA, a powerful integrated development tool. This software is charged. I believe everyone knows it. I won't say more.

2. Prepare the database

Since it is written in Java, MySQL must be used. As for how to download, install and configure mysql, you can refer to the articles of other leaders. I won't say more here.

3. Prepare for outsourcing

Because you want to use jdbc technology, you must import an outsourcing to connect to MySQL. You can search and download it on the Internet. I will elaborate on the specific operation process below.

3, Specific steps

1. Open IDEA and create an empty project

 2. After completion, import a new module

 

Build these three packages while importing the new module.

3. Import the outsourcing jar package to be used by JDBC.

Just import it here, click the plus sign, and then find the connection package you downloaded, which contains a jar package.

In this way, all kinds of complex environments are ready, and then you just need to write code.

4, Code implementation

1. Interface class

1.1 login interface

The first is the login interface. Considering the login interface, we need to enter the user name and password, as well as a login button and a registration button. How to realize prompt after login and other operations? Then you need to add mouse monitoring.

package com.jdbc.ui;

import com.jdbc.connecter.ConectMysqlforlogin;
import com.jdbc.connecter.ConectMysqlforsign;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class CreateLoginUI extends JFrame implements MouseListener {
    JButton btn1=new JButton("Sign in");//Define login button
    JButton btn2=new JButton("register");//Define registration button
    JTextField usernamefield=new JTextField();//Set the text box for entering the user name
    JTextField passwordfeild=new JTextField();//Sets the text box for entering a password
    JLabel label1=new JLabel("user name:");
    JLabel label2=new JLabel("password:");
    /**
     * Construction method with parameters
     * @param width Sets the width of the form
     * @param height Sets the height of the form
     * @param defaultOperation Set the default closing method
     */
    public CreateLoginUI(String title, int width, int height, int defaultOperation){
        setTitle(title);
        setSize(width,height);
        setDefaultCloseOperation(defaultOperation);
        setLayout(null);
        setLocationRelativeTo(null);

        //Add login button
        btn1.setBackground(Color.yellow);
        btn1.setBounds(0,height/8,width/10*3,height/10);
        getContentPane().add(btn1);
        btn1.addMouseListener(this);

        //Add registration button
        btn2.setBackground(Color.blue);
        btn2.setBounds(width/10*3,height/8,width/10*3,width/10);
        getContentPane().add(btn2);
        btn2.addMouseListener(this);

        //Add user name and password
        label1.setBounds(0,0,width/10,height/16);
        getContentPane().add(label1);
        label2.setBounds(0,height/16,width/10,height/16);
        getContentPane().add(label2);

        //Add text box
        usernamefield.setBounds(width/10,0,width/2,height/16);
        passwordfeild.setBounds(width/10,height/16,width/2,height/16);
        getContentPane().add(usernamefield);
        getContentPane().add(passwordfeild);

        setVisible(true);
    }

    /**
     * Set mouse click action
     * @param e
     */
    @Override
    public void mouseClicked(MouseEvent e) {
        Object obj=e.getSource();
        if(obj==btn1){
            ConectMysqlforlogin conectMysqlforlogin=new ConectMysqlforlogin(usernamefield.getText(),passwordfeild.getText());
            if(conectMysqlforlogin.isIn==true){
                showUI showSL=new showUI("Login succeeded");
            }
            else{
                showUI showFL=new showUI("Login failed");
            }
        }
        else if(obj==btn2){
            CreateSignUI signUI=new CreateSignUI("Registration interface",400,400);
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}

1.2 registration interface

Similarly, the registration interface also needs the input box of user name and password and an OK button.

package com.jdbc.ui;

import com.jdbc.connecter.ConectMysqlforsign;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowListener;

public class CreateSignUI extends JFrame implements MouseListener {
    JTextField usernamefield=new JTextField();//Set the text box for entering the user name
    JTextField passwordfeild=new JTextField();//Sets the text box for entering a password
    JLabel label1=new JLabel("user name:");
    JLabel label2=new JLabel("password:");
    JButton btn=new JButton("determine");

    public CreateSignUI(String title,int width,int height){
        setSize(width,height);
        setTitle(title);
        setDefaultCloseOperation(2);
        setLocationRelativeTo(null);
        setLayout(null);

        btn.setBackground(Color.white);
        btn.setBounds(0,height/8,width/10*3,height/10);
        getContentPane().add(btn);
        btn.addMouseListener(this);

        //Add user name and password
        label1.setBounds(0,0,width/10,height/16);
        getContentPane().add(label1);
        label2.setBounds(0,height/16,width/10,height/16);
        getContentPane().add(label2);

        //Add text box
        usernamefield.setBounds(width/10,0,width/2,height/16);
        passwordfeild.setBounds(width/10,height/16,width/2,height/16);
        getContentPane().add(usernamefield);
        getContentPane().add(passwordfeild);

        setVisible(true);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        ConectMysqlforsign conectMysqlforsign=new ConectMysqlforsign(usernamefield.getText(),passwordfeild.getText());
        if(conectMysqlforsign.count==1){

        }
        else{
            showUI showFS=new showUI("User name already exists");
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}

1.3 prompt window

Finally, how to prompt whether it has been successful or not.

package com.jdbc.ui;

import javax.swing.*;

public class showUI extends JFrame {
    public showUI(String title){
        setSize(100,100);
        setDefaultCloseOperation(2);
        setLocationRelativeTo(null);
        setTitle(title);

        JLabel label=new JLabel(title,SwingConstants.CENTER);
        getContentPane().add(label);

        setVisible(true);
    }
}

 2. Connection class

2.1 login connection

Log in and connect to MySQL, and then realize the query operation. If the user name and password are in the database, you can log in successfully.

package com.jdbc.connecter;

import java.sql.*;

public class ConectMysqlforlogin {
    private String url="jdbc:mysql://localhost:3306/inf";
    private String user="root";
    private String psd="zqh123";
    public Boolean isIn=false;

    Connection conn1 =null;
    PreparedStatement ps1 =null;
    ResultSet rs1 =null;

    public ConectMysqlforlogin(String user, String password){
        try {
            //Register driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            //Connect to database
            conn1 =DriverManager.getConnection(url,this.user,psd);
            //Database precompiling operation object acquisition
            String sql="select * from t_user where username=? and password=?";
            ps1 = conn1.prepareStatement(sql);
            ps1.setString(1,user);
            ps1.setString(2,password);
            //Execute sql statement
            rs1=ps1.executeQuery();
            if(rs1.next()){
                isIn=true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(rs1 !=null){
                try {
                    rs1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps1 !=null){
                try {
                    ps1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn1 !=null){
                try {
                    conn1.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.2 registered connection class

To register and connect to the database, you should realize the insertion operation. If an account has been registered in the database, you should also be prompted.

package com.jdbc.connecter;

import java.sql.*;

public class ConectMysqlforsign {
    private String url="jdbc:mysql://localhost:3306/inf";
    private String user="root";
    private String psd="zqh123";

    Connection conn2 =null;
    PreparedStatement ps2 =null;
    ResultSet rs2 =null;
    Statement stmt=null;
    public int count=0;

    public ConectMysqlforsign(String user, String password){
        try {
            //Register driver
            Class.forName("com.mysql.cj.jdbc.Driver");
            //Connect to database
            conn2 = DriverManager.getConnection(url,this.user,psd);
            //Database precompiling operation object acquisition
            String sql1="INSERT into t_user(username,password) values(?,?)";
            String sql2="select * from t_user where username='"+user+"'";
            stmt=conn2.createStatement();
            rs2=stmt.executeQuery(sql2);
            if(!rs2.next()){
            ps2 = conn2.prepareStatement(sql1);
            ps2.setString(1,user);
            ps2.setString(2,password);
            count=ps2.executeUpdate();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(rs2 !=null){
                try {
                    rs2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps2 !=null){
                try {
                    ps2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn2 !=null){
                try {
                    conn2.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

3. Testing

package com.jdbc.test;


import com.jdbc.ui.CreateLoginUI;

public class JDBCTest1{
    public static void main(String[] args) {
        CreateLoginUI ui=new CreateLoginUI("User login interface",400,400,3);
    }
}

5, Final effect display

In addition, it should be noted that the user name and password to connect to the database and the database used are different from each other, so don't copy my code.

Rough interface, ha ha

 

It means that there is no such account in the database

 

 

 

6, Summary

In short, what I wrote is very delicious. In fact, the password field can be changed to password type, so that the content you entered will not be displayed. In fact, it can be improved in the later stage. This is my first blog, ha ha.

Keywords: Java JDBC JavaSE swing

Added by meir4u on Tue, 21 Dec 2021 14:35:53 +0200