Simulated bank deposit and withdrawal business (GUI version)

1, Experimental purpose

(1) Comprehensively test the idea of object-oriented programming and consolidate the application of Java object-oriented, collection and common API classes;
(2) Strengthen practical ability and be able to apply the theoretical knowledge learned from books to practice.

2, Experimental content

Simulate online banking business. When users log in, they need to judge the bank card number and bank card password. When the entered card number and password are correct, they will log in successfully, prompt the currently logged in account name, and enter the next step to select the operation type. There are four operation types (deposit: 1 withdrawal: 2 balance: 3 modify personal password: 4 exit: 0). When you enter the numbers 1 and 2, the deposit and withdrawal operation will be carried out. At this time, you need to enter the deposit and withdrawal amount and calculate the correct amount addition and subtraction; When the number 3 is entered, the balance of the current account is displayed; When the number 4 is entered, the password of the current account can be modified; Entering the number 0 will exit the entire system. Tip: you can use the HashMap set to store the simulated account information, where the key value is used to store the bank card number and the value value is used to store the whole account object.

3, Overall design (design principle, design scheme and process, etc.)

Structure:
There are four packages in this experiment
1.image to place the picture package,
2.DataBase simulates the account information in the banking system, which is equivalent to the function of database,
3. The login interface implementation class and bank operation interface implementation class are placed in the frame, and a simple GUI is used to realize the logical structure,
4.module to place user model classes
There is also a properties file that can read data into the file

Design principle:
1. Put the bank user into a hashMap. Each time you enter and exit the program, the data in the hashMap table will be read into the properties file to achieve the function of retaining data.
2. The user can log in only after entering the correct userName and passWord. The bank interface can deposit, withdraw, view the balance, modify the account passWord, etc. the effect can be achieved by modifying the data in the hashMap table, and then saving it into the properties file to retain the data, so as to ensure that the data can be restored when logging in next time

4, Code implementation

package BankManagementSystem.DataBase;


import BankManagementSystem.model.User;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

/**
 * @author Wang Jie
 * @date 2021/11/23 15:09
 * @details Simulate the account information in the banking system, which is equivalent to the function of the database
 */
public class DataBaseUtil {
    private static DataBaseUtil instance = null;
    private static HashMap<String, User> users = new HashMap<>();

    private DataBaseUtil(){
        Properties pro =new Properties();//Act as a simple database

        try {
            pro.load(new FileReader("src/data.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        int allNum = Integer.parseInt(pro.getProperty("allNum"));
        for(int i=1;i <= allNum;i++){
            User user = new User();
            user.setCardId(pro.getProperty(i+"-id"));
            user.setCardPwd(pro.getProperty(i+"-pwd"));
            user.setAccount(Integer.parseInt(pro.getProperty(i+"-account")));
            user.setCallNum(pro.getProperty(i+"-callNum"));
            user.setUserName(pro.getProperty(i+"-name"));
            users.put(user.getCardId(),user);//Add to collection

        }
        /*
        User user01 = new User();
        user01.setUserName("WJ");
        user01.setCardId("123456");
        user01.setCardPwd("123456");
        user01.setCallNum("000000");
        user01.setAccount(1000);
        users.put(user01.getCardId(),user01);

        User user02 = new User();
        user02.setUserName("XXY");
        user02.setCardId("1234567");
        user02.setCardPwd("1234567");
        user02.setCallNum("0000000");
        user02.setAccount(1000);
        users.put(user02.getCardId(),user02);

        User user03 = new User();
        user03.setUserName("gubao");
        user03.setCardId("12345678");
        user03.setCardPwd("12345678");
        user03.setCallNum("00000000");
        user03.setAccount(1000);
        users.put(user03.getCardId(),user03);*/
    }

    public static DataBaseUtil getInstance(){//Lazy singleton mode makes all objects unique
        if(instance == null){//Synchronization code block p371
            synchronized (DataBaseUtil.class){
                instance = new DataBaseUtil();
            }
        }
        return instance;
    }

    //Obtain user personal information according to id
    public static User getUser(String userName){
        return users.get(userName);
    }

    //Get hashMap
    public static HashMap<String,User> getUsers(){
        return users;
    }

    public static boolean CheckLogin(String userName,String passWord){
        Set set = users.keySet();
        Iterator it = set.iterator();
        while(it.hasNext()){
            String userid = (String) it.next();
            User user = users.get(userid);
            //Determine whether the id is consistent with the password
            if(userid.equals(userName) && user.getCardPwd().equals(passWord)){
                return true;
            }
        }
        return false;
    }



}

package BankManagementSystem.frame;

import BankManagementSystem.DataBase.DataBaseUtil;
import BankManagementSystem.model.User;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Properties;
import java.util.Vector;

/**
 * @author Wang Jie
 * @date 2021/11/30 11:38
 * @details Simple implementation of the bank panel, and some basic operations (saving, withdrawing, balance, changing password)
 */
public class BankFrame extends JFrame {
    private User user;
    Properties pro = new Properties();//Act as a simple database
    int index;//Database index
    JPanel contentPane;
    JScrollPane scp = new JScrollPane();
    JTable tab = null;
    String text;//Text data
    Vector CellsVector = new Vector();// Title Line
    Vector TitleVector = new Vector();// data row
    JButton btn_save = new JButton("save money");
    JButton btn_withdraw = new JButton("Withdraw money");
    JButton btn_remain = new JButton("balance");
    JButton btn_set_passWord = new JButton("Change Password");

    JTextField text_context = new JTextField();//Input content

    JLabel context = new JLabel("Enter the relevant number: ");

    public BankFrame(String userName){


        try {//Load database
            pro.load(new FileReader("src/data.properties"));
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        index = getUserIndex(userName);
        //Get user object
        user = DataBaseUtil.getUser(userName);
        //Settings of JPanel panel
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        this.setResizable(false);
        setSize(new Dimension(600, 340));
        setLocationRelativeTo(null);
        setTitle(user.getUserName() + "user");
        //Setting of sliding panel
        scp.setBounds(new Rectangle(46, 32, 497, 157));
//        Coordinate establishment of JLabel
        context.setFont(new Font("Song typeface", Font.BOLD, 14));
        context.setBounds(136,200,126,20);
        //Coordinate establishment of Text
        text_context.setBounds(255,200,130,20);
        text_context.setFont(new Font("Song typeface", Font.BOLD, 14));
        text_context.setDocument(new JTextFieldLimit(12));//Limit password length to 12

        //Button coordinate establishment
        btn_save.setBounds(new Rectangle(85, 271, 70, 25));
        btn_save.setFont(new Font("Song typeface", Font.BOLD, 12));
        btn_save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(checkInformation()){
                    Integer num =Integer.valueOf(text);
                    user.setAccount(user.getAccount()+num);//Deposit user deposit
                    DataBaseUtil.getUsers().put(user.getCardId(),user);//Stored in database
                    pro.setProperty(index+"-account",String.valueOf(user.getAccount()));
                    try {
                        pro.store(new FileWriter("src/data.properties"),"Modify value");
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");
                    Vector vector = new Vector();
                    vector.add("deposit");
                    vector.add(num);
                    vector.add(now.format(dtf));
                    CellsVector.add(vector);
                    tab.updateUI();
                }
            }
        });
        btn_withdraw.setBounds(195, 271, 70, 25);
        btn_withdraw.setFont(new Font("Song typeface", Font.BOLD, 12));
        btn_withdraw.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(checkInformation()){
                    Integer num =Integer.valueOf(text);
                    if(num > user.getAccount()){//Judge insufficient balance
                        JOptionPane.showMessageDialog(contentPane, "Hello!!Your account balance is insufficient!", "Tips", 1);
                        text_context.setText("");
                        return;
                    }

                    user.setAccount(user.getAccount()-num);//Deposit user deposit
                    DataBaseUtil.getUsers().put(user.getCardId(),user);//Stored in database
                    pro.setProperty(index+"-account",String.valueOf(user.getAccount()));
                    try {//Load the properties into the corresponding file
                        pro.store(new FileWriter("src/data.properties"),"Modify value");
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");
                    Vector vector = new Vector();
                    vector.add("withdraw money");
                    vector.add(num);
                    vector.add(now.format(dtf));
                    CellsVector.add(vector);
                    tab.updateUI();
                }
            }
        });
        btn_remain.setBounds(new Rectangle(295, 271, 70, 25));
        btn_remain.setFont(new Font("Song typeface", Font.BOLD, 12));
        btn_remain.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");
                Vector vector = new Vector();
                vector.add("Account balance");
                vector.add(user.getAccount());
                vector.add(now.format(dtf));
                CellsVector.add(vector);
                tab.updateUI();
                text_context.setText("");
            }
        });
        btn_set_passWord.setBounds(395, 271, 120, 25);
        btn_set_passWord.setFont(new Font("Song typeface", Font.BOLD, 12));
        btn_set_passWord.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //Check operation
                text = text_context.getText();
                if (text.equals("")) {//If it is empty, enter a warning
                    JOptionPane.showMessageDialog(contentPane, "Hello! Please input a password!", "Tips", 1);
                    text_context.grabFocus();
                    return;
                }
                user.setCardPwd(text);//Database change password
                DataBaseUtil.getUsers().put(user.getCardId(),user);
                JOptionPane.showMessageDialog(contentPane, "Modification succeeded! Account name:"+ user.getUserName() + " password:" +user.getCardPwd(), "Tips", 1);
                pro.setProperty(index+"-pwd",String.valueOf(user.getCardPwd()));
                try {
                    pro.store(new FileWriter("src/data.properties"),"Modify value");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                System.out.println(pro.getProperty("1-pwd"));
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");
                Vector vector = new Vector();
                vector.add("Change Password");
                vector.add("Modified successfully");
                vector.add(now.format(dtf));
                CellsVector.add(vector);
                tab.updateUI();
                text_context.setText("");
            }
        });

        //Add components to JPanel
        contentPane.add(scp);
        contentPane.add(btn_save);
        contentPane.add(btn_withdraw);
        contentPane.add(btn_remain);
        contentPane.add(btn_set_passWord);
        contentPane.add(context);
        contentPane.add(text_context);
        this.TitleVector.add("Query operation");
        this.TitleVector.add("Operating amount(RMB yuan)");
        this.TitleVector.add("Operation time");

        tab = new JTable(CellsVector, TitleVector);
        scp.getViewport().add(tab);
        this.add(scp,BorderLayout.CENTER);
        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


    // Verify the input box
    public boolean checkInformation() {
        text = text_context.getText();

        if (text.equals("")) {//If it is empty, enter a warning
            JOptionPane.showMessageDialog(contentPane, "Hello! Please enter the amount!", "Tips", 1);
            text_context.grabFocus();
            return false;
        }
        char[] ans = text.toCharArray();
        for (int i = 0; i < ans.length; i++) {//Traverse each character
            if (!Character.isDigit(ans[i])) {//If it is not a digital output, a warning is output
                JOptionPane.showMessageDialog(contentPane, "Hello! The amount can only be numbers!", "Tips", 1);
                text_context.setText("");
                text_context.grabFocus();
                return false;
            }
            if (text.length() > 5) {
                JOptionPane.showMessageDialog(contentPane, "Hello!! The deposit cannot exceed 99999 yuan", "Tips", 1);
                text_context.setText("");
                text_context.grabFocus();
                return false;
            }
        }
        text_context.setText("");
        return true;
    }

    //Get the corresponding user from Properties
    private int getUserIndex(String userId){
        int i = Integer.parseInt(pro.getProperty("allNum"));
        for(int j=1;j <= i ;j++){
            if(pro.getProperty(j+"-id").equals(userId)){
                return j;
            }
        }
        return -1;
    }
}

package BankManagementSystem.frame;

import BankManagementSystem.DataBase.DataBaseUtil;

import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;

/**
 * @author Wang Jie
 * @date 2021/11/30 11:38
 * @details Implementation class of login interface
 */
public class LoginFrame extends JFrame {
    /**
     * user name
     */
    private static final JLabel usernameLabel = new JLabel("user name(Less than 12 bits)");
    private static final JTextField usernameInput = new JTextField();

    /**
     * password
     */
    private static final JLabel passwordLabel = new JLabel("password(Less than 12 bits)");
    private static final JTextField passwordInput = new JPasswordField();
    /**
     * Login and exit buttons
     */
    private static final JButton loginButton = new JButton(new ImageIcon("image/login.png"));//Use pictures
    //	private static final JButton loginButton = new JButton("login");
    private static final JButton exitButton = new JButton("register   ");




    public LoginFrame() {
        setSize(new Dimension(380, 180));
        setLocationRelativeTo(null);



        // Sets the title of the form
        setTitle("Bank login system");
        setLayout(null);

        //Initialization interface
        initUI();

        // Click close to exit the program
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Set form visibility
        setVisible(true);

        //Loading of database
        DataBaseUtil.getInstance();

        // This is designed as the listening of login button
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Gets the values of the user name and password input boxes
                String userName = usernameInput.getText().trim();
                String passWord = passwordInput.getText().trim();

                // Prompt the user for input when the user name is empty
                if ("".equals(userName)) {
                    //JOptionPane can easily pop up a standard dialog box,
                    // Prompt users to get values or notify them of something.
                    JOptionPane.showMessageDialog(LoginFrame.this, "enter one user name");
                    return;
                }
                // Prompt the user when the password is empty
                if ("".equals(passWord)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "Please input a password");
                    return;
                }

                // query data base
                if (!DataBaseUtil.CheckLogin(userName, passWord)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "Wrong user name or password");
                    return;
                }

                // Close the current interface first
                dispose();
                // Open user management interface
                new BankFrame(userName);
            }
        });

        // This place is designed as the monitoring of exit button
        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }


    /**
     * Initialization interface
     */
    private void initUI() {
        usernameInput.setDocument(new JTextFieldLimit(12));
        passwordInput.setDocument(new JTextFieldLimit(12));

        usernameLabel.setBounds(10, 10, 100, 21);
        usernameInput.setBounds(150, 10, 200, 21);
        passwordLabel.setBounds(10, 40, 100, 21);
        passwordInput.setBounds(150, 40, 200, 21);
        loginButton.setBounds(60, 100, 120, 21);
        exitButton.setBounds(200, 100, 120, 21);

        add(usernameLabel);
        add(usernameInput);
        add(passwordLabel);
        add(passwordInput);
        add(loginButton);
        add(exitButton);
    }



    //Start entry
    public static void main(String[] args) {
        new LoginFrame();
    }

}


//Class that limits input length
class   JTextFieldLimit extends PlainDocument {

    private int limit;  //Limited length

    public JTextFieldLimit(int limit) {
        super(); //Call parent class construction
        this.limit = limit;
    }
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if(str == null) return;

        //The following judgment conditions can be changed to the conditions you want to limit. Here is to limit the input length
        if((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);//Call parent method
        }
    }

}
package BankManagementSystem.model;

/**
 * @author Wang Jie
 * @date 2021/11/23 15:01
 * @details User information class
 */
public class User {
    private String cardId;//User id
    private String cardPwd;//User password
    private String userName;//user name
    private String callNum;//User telephone number
    private int account;//User account balance

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public String getCardPwd() {
        return cardPwd;
    }

    public void setCardPwd(String cardPwd) {
        this.cardPwd = cardPwd;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getCallNum() {
        return callNum;
    }

    public void setCallNum(String callNum) {
        this.callNum = callNum;
    }

    public int getAccount() {
        return account;
    }

    public void setAccount(int account) {
        this.account = account;
    }
}

There is also a data Don't forget to create the properties file under the src package and add the data line of allNum=0!

5, Result analysis and summary


Keywords: Java

Added by apw on Sat, 11 Dec 2021 03:49:52 +0200