Login registration interface test

Keywords: Java

Make a simple login registration page

In the past few days, I have learned about the java graphical user interface (GUI) and started to make a simple login interface. I don't talk much nonsense

1. Login interface

The so-called design of a UI interface is nothing more than two layered modules: one UI display design involves some aesthetic considerations, which is reflected in component selection and component layout, and the other is the logic executed after triggering and listening of the UI interface.

(1) Login UI object

1. Create a window JFrame: including title, window size, default closing method, and default outgoing call location

2. Add flow layout to the window; (equivalent to streaming layout in css)

3. Create various small components: including label JLabel, text input box JTextField and button Jbutton

4. Use add to add various widgets to the window

5. Display UI: setVisible (true)

6. Create a listener object (listener object implemented below)

7. Assign listeners to each button;

package LoginService.MyLoginWindow;

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

public class MyLoginUI {
    public static void showMyUI(){
        //Building windows
        javax.swing.JFrame jf=new JFrame();
        jf.setTitle("Login interface");
        jf.setSize(450,300);
        jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        jf.setLocation(500,300);//Open position
        //Add flow layout
        FlowLayout fl=new FlowLayout();
        jf.setLayout(fl);
        //Build widget
        javax.swing.ImageIcon img = new javax.swing.ImageIcon ("C:\\Users\\Public\\Pictures\\T.PNG");
        javax.swing.JLabel imgJla = new javax.swing.JLabel (img);//Picture display area

        javax.swing.JButton loginBtn1=new JButton("Sign in");
        javax.swing.JButton signBtn1=new JButton("register");
        javax.swing.JLabel nullLabel=new JLabel("                " +
                "                                                                                         ");//Text display area
        javax.swing.JLabel nameLabel=new JLabel("user name:");//Text display area
        javax.swing.JLabel passWordLabel=new JLabel("password:");//Text display area

        javax.swing.JTextField nameField = new javax.swing.JTextField ();//Input box
        java.awt.Dimension dim = new java.awt.Dimension (350, 30);
        nameField.setPreferredSize (dim);   //Set input box size
        javax.swing.JTextField passWordField = new javax.swing.JTextField ();//Input box
        passWordField.setPreferredSize (dim);   //Set input box size
        //Add small components
        jf.add(imgJla);
        jf.add(nullLabel);
        jf.add(nameLabel);
        jf.add(nameField);
        jf.add(passWordLabel);
        jf.add(passWordField);
        jf.add(loginBtn1);
        jf.add(signBtn1);
        //Display UI
        jf.setVisible(true);
        //Create listening object
        MyButtonAction myButtonAction=new MyButtonAction();
        //Assign a value to the input box object of the listening object
        myButtonAction.nameField=nameField;
        myButtonAction.passWordField=passWordField;

        //Add listening objects to each button
        loginBtn1.addActionListener(myButtonAction);
        signBtn1.addActionListener(myButtonAction);
        //Create login service
        LoginService loginService=new LoginService();
        //Create registration service
    }
    public static void main(String[] args) {
        showMyUI();
    }
}

(2) Implement a listener object

The principle of the so-called listener is similar to the recovery monitoring in the JVM. The specific principle is not discussed in this film;

The listener implements the ActionListener interface. The main process is to rewrite the actionPerformed method, that is, the method to be executed after the listener is triggered. In this example, it is necessary to continuously monitor the situation of each button, but the interesting thing here is that instead of the listener accepting each monitored button, each button specifies the listener;

When the actionPerformed method is defined in the interface, there is a parameter ActionEvent e, that is, when the actionPerformed method is called, a package for the trigger event will be passed in. The ID of the trigger button can be obtained through e.getActionCommand(). The listener itself does not know which button triggered it, so it needs to judge the button ID in the rewritten method.

It is worth mentioning that the listener MyButtonAction also needs to obtain the input content in the text box. Here, you can choose to create a corresponding class in the listener. After the listener is created, execute the assignment of the corresponding class (see MyLoginUI code). Of course, you can also use the

package LoginService.MyLoginWindow;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import LoginService.SigninService.SigninService;

public class MyButtonAction implements ActionListener {
    //Login is indicated by a text object
    JTextField nameField;
    JTextField passWordField;
	//Text object indication for registration
    JTextField signNameField;
    JTextField signPassWordField;
    JTextField signGenderField;
    JTextField signAgeField;
    JTextField signPhoneNumField;

    int count=0;
    @Override
    public void actionPerformed(ActionEvent e) {
        count++;
        String btnText=e.getActionCommand();//Get trigger button ID
        String inText=nameField.getText();//Get input box text
        System.out.println("The first"+count+"Press the button once");
        System.out.println("Input box content:"+inText);

        if(btnText.contains("Sign in")) {
            LoginService.isLegel(nameField,passWordField);
        }

        if(btnText.equals("register")){
            SigninService signinService=new SigninService();
            signinService.actionListener=this;//Pass the listener into the user registration service class object
            signinService.Signin();
        }
        if(btnText.equals("Register now")){
    		SigninService.writeUser(signNameField,signPassWordField,
                            signGenderField,signAgeField,signPhoneNumField);
        }
    }
}

(3) Effect display

2. Add registration function

The above introduction to the login UI does not involve the description of work functions. What we can do is to make classification reactions according to text input boxes and buttons. The process from registering and adding users to successful login is not realized.

On this basis, if you want to achieve the interaction between registration and login, you must design user classes, login services (services provided after clicking the login button), registration services (services provided after clicking the registration button), etc. At the same time, it also includes the design of registration UI.

The following is the frame display of the whole UI

(1) About User class User

Here, the verification method of user information is implemented in the user class, so as to try to check who has the information, so as to reduce the coupling between classes.
In practical application, taking QQ as an example, if the user enters the wrong password many times, the security check of the user object can be initiated.

package LoginService.MyUser;

public class User {
    private String Name;
    private String passWord;
    private boolean gender;//0-female,1-male
    private int age;
    private String phoneNum;
    private int isOn=0;//Online status description


    public User(String name, String passWord, boolean gender, int age, String phoneNum) {
        Name = name;
        this.passWord = passWord;
        this.gender = gender;
        this.age = age;
        this.phoneNum = phoneNum;
    }
    
	//..............................
	//A series of get, set, and toString methods are omitted here
    
    public boolean checkPassWord(String pw){
        return this.passWord.equals(pw);
    }

    public boolean isMessageLegal(){
        return !Name.isEmpty()&&!passWord.isEmpty()&&age>=0&&!phoneNum.isEmpty();
    }
}

(2) About user service class LoginService

The data of the User service class mainly includes: the static array storing the User object (the reason for static is very simple)

The main functions include: receiving the information of the packed text box, finding out whether the User exists, modifying the User array, and calling the User's password check method

The user service class must be instantiated during UI initialization to ensure that the service of the user service class is obtained when clicking the login button.

package LoginService.MyLoginWindow;

import LoginService.MyUser.User;
import LoginService.PopUpWindowPattern.LoginSucceedPopUpWindow;
import LoginService.PopUpWindowPattern.PopUpWindow;
import LoginService.PopUpWindowPattern.passWordWrongPopUpWindow;
import LoginService.PopUpWindowPattern.userUnExistPopUpWindow;
import javax.swing.*;

public class LoginService {
    static User[] userList=new User[100];
    static int userNum=0;
    static final int MAXNUM=100;
	//For testing, join the initial user
    public LoginService() {
        for(int i=0;i<10;i++){
            userList[i]=new User("user"+i,""+i);
            userNum++;
        }
    }
	//User existence judgment
    public static int isUserExist(JTextField userNameField, JTextField passWordField){
        String name=userNameField.getText();
        for(int i=0;i<userNum;i++){
            if(userList[i].getName().equals(name)){
                return i;
            }
        }
        return -1;
    }
	//Judge the legitimacy of user account and password, and log in successfully if it is legal
    public static void isLegel(JTextField userNameField, JTextField passWordField){
        int pos=isUserExist(userNameField,passWordField);
        if(pos>=0){
            if(userList[pos].checkPassWord(passWordField.getText())){
                new PopUpWindow().popUp(new LoginSucceedPopUpWindow());
                userList[pos].setIsOn(1);//Modify online status
            }
            else{
                new PopUpWindow().popUp(new passWordWrongPopUpWindow());
            }
        }
        else{
            new PopUpWindow().popUp(new userUnExistPopUpWindow());
        }

    }
    //Write user
    public static boolean writeUserInList(User user){
        if(userNum>=MAXNUM){
            return false;
        }
        else {
            userList[userNum] = user;
            userNum++;
            return true;
        }
    }

}

(3) About user registration services

main

package LoginService.SigninService;
import LoginService.MyLoginWindow.LoginService;
import LoginService.MyLoginWindow.MySigninUI;
import LoginService.MyUser.User;
import LoginService.PopUpWindowPattern.*;

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

public class SigninService {
    public ActionListener actionListener;
    MySigninUI mySigninUI;
	//Instantiate the registered UI object, pass in the listener, and display
    public void Signin(){
        MySigninUI mySigninUI=new MySigninUI();
        mySigninUI.setActionListener(actionListener);
        mySigninUI.showMySigninUI();
    }
    //Registration function
    public static void writeUser(JTextField signNameField,JTextField signPassWordField,JTextField signGenderField,
                                  JTextField signAgeField,JTextField signPhoneNumField){
        String name=signNameField.getText();
        String passWord=signPassWordField.getText();
        boolean gender=Integer.parseInt(signGenderField.getText())!=0;
        int age=Integer.parseInt(signAgeField.getText());
        String phoneNum=signPhoneNumField.getText();

        User user=new User(name,passWord,gender,age,phoneNum);
        if(user.isMessageLegal()){
            //Write login service
            if(LoginService.writeUserInList(user)){
                new PopUpWindow().popUp(new SigninSucceedPopUpWindow());
            }
            else{
                System.out.println("User full");
            }
        }
        else{
            new PopUpWindow().popUp(new MessageIllegalPopUpWindow());
        }

    }

(4) Register UI

package LoginService.MyLoginWindow;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;

public class MySigninUI {
    public ActionListener actionListener;

    public void setActionListener(ActionListener actionListener) {
        this.actionListener = actionListener;
    }

    public void showMySigninUI() {
        //Building windows
        javax.swing.JFrame jf = new JFrame();
        jf.setTitle("Registration interface");
        jf.setSize(450, 500);
        jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        jf.setLocation(600, 250);//Open position
        //Add flow layout
        FlowLayout fl=new FlowLayout();
        jf.setLayout(fl);
        //Build widget
        javax.swing.ImageIcon img = new javax.swing.ImageIcon ("C:\\Users\\Public\\Pictures\\T.PNG");
        javax.swing.JLabel imgJla = new javax.swing.JLabel (img);//Picture display area
        javax.swing.JButton signBtn1=new JButton("Register now");//Button
        javax.swing.JLabel nullLabel=new JLabel("                " +
                "                                                                                         ");//Text display area
        javax.swing.JLabel nameLabel=new JLabel("user name:");//Text display area
        javax.swing.JLabel passWordLabel=new JLabel("password:");//Text display area
        javax.swing.JLabel genderLabel=new JLabel("Gender:");//Text display area
        javax.swing.JLabel ageLabel=new JLabel("Age:");//Text display area
        javax.swing.JLabel phoneNumLabel=new JLabel("phone number:");//Text display area

        javax.swing.JTextField nameField = new javax.swing.JTextField ();//user name
        javax.swing.JTextField passWordField = new javax.swing.JTextField ();//password
        javax.swing.JTextField genderField = new javax.swing.JTextField ();//Gender
        javax.swing.JTextField ageField = new javax.swing.JTextField ();//Age
        javax.swing.JTextField phoneNumField = new javax.swing.JTextField ();//cell-phone number
        java.awt.Dimension dim = new java.awt.Dimension (350, 30);
        nameField.setPreferredSize (dim);   //Set input box size
        passWordField.setPreferredSize(dim);
        genderField.setPreferredSize(dim);
        ageField.setPreferredSize(dim);
        phoneNumField.setPreferredSize(dim);

        //Add small components
        jf.add(imgJla);
        jf.add(nullLabel);
        jf.add(nameLabel);
        jf.add(nameField);
        jf.add(passWordLabel);
        jf.add(passWordField);
        jf.add(genderLabel);
        jf.add(genderField);
        jf.add(ageLabel);
        jf.add(ageField);
        jf.add(phoneNumLabel);
        jf.add(phoneNumField);
        jf.add(signBtn1);
        //display
        jf.setVisible(true);
        //Add listening object
        MyButtonAction myButtonAction=(MyButtonAction)actionListener;
        signBtn1.addActionListener(myButtonAction);

        //Input box assignment
        myButtonAction.signNameField=nameField;
        myButtonAction.signPassWordField=passWordField;
        myButtonAction.signGenderField=ageField;
        myButtonAction.signAgeField=ageField;
        myButtonAction.signPhoneNumField=phoneNumField;

    }
}

(5) Pop up class description

It can be found from the above code that I have created a fancy pop-up class to collect the tips of all situations through the interface. Once a pop-up class is needed, I can create a pop-up class object, call its pop-up method, and pass parameters into various implemented objects of the interface to realize the management of pop-up.

new PopUpWindow().popUp(new SigninSucceedPopUpWindow());//Registration successful pop-up
//Pop up method interface
public interface PopUpWindowInterface {
    void popUpWindow();
}
//Pop up class
public class PopUpWindow {
    public void popUp(PopUpWindowInterface ppwindow){
        ppwindow.popUpWindow();
    }
}
//Implementation of pop-up method interface
//login was successful
public class SigninSucceedPopUpWindow implements PopUpWindowInterface {
    @Override
    public void popUpWindow() {
        javax.swing.JFrame jf = new JFrame();
        jf.setTitle("success");
        jf.setSize(100, 100);
        jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        jf.setLocation(400, 250);//Open position
        javax.swing.JLabel nameLabel=new JLabel("login was successful");//Text display area
        jf.add(nameLabel);
        jf.setVisible(true);
    }
}

It can be found that if you want to write many pop-up implementations, there will be a lot of duplicate code, so package this part of the code

//Pop up method interface
public interface PopUpWindowInterface {
    void popUpWindow();
}
//Pop up class
public class PopUpWindow {
    public void popUp(PopUpWindowInterface ppwindow){
        ppwindow.popUpWindow();
    }
    public static void popUpMethod(String title,String context){
        javax.swing.JFrame jf = new JFrame();
        jf.setTitle(title);
        jf.setSize(100, 100);
        jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        jf.setLocation(400, 250);//Open position
        javax.swing.JLabel nameLabel=new JLabel(context);//Text display area
        jf.add(nameLabel);
        jf.setVisible(true);
    }
}
//Implementation of pop-up method interface
//login was successful
public class SigninSucceedPopUpWindow implements PopUpWindowInterface {
    @Override
    public void popUpWindow() {
		PopUpWindow.popUpMethod("success","Login succeeded");
    }
}

(6) Effect display


Posted by drew69 on Mon, 29 Nov 2021 14:06:09 -0800