模拟银行存取款业务(GUI版)

一、实验目的

(1)全面检验面向对象编程思想,巩固Java面向对象、集合和常用API类等方面知识的应用;
(2)加强实践动手能力,能够将从书本上学习到的理论知识用到了实践上。

二、实验内容

模拟网上银行业务,当用户登录时需判断银行卡号和银行卡密码,当输入的卡号和密码都正确时,登录成功,提示当前登录的账户名,并进入下一步选择操作类型。操作类型包括四种(存款:1 取款:2 余额:3 修改个人密码:4 退出:0),输入数字1、2时,将进行存取款操作,此时需要输入存取的金额,并进行正确的金额加减计算;输入数字3时,显示当前账户的余额;输入数字4时,可修改当前账户的密码;输入数字0时将退出整个系统。提示:可利用HashMap集合存储模拟的账户信息,其中key值用于存储银行卡号,value值用于存储整个账户对象。

三、总体设计(设计原理、设计方案及流程等)

结构:
该实验共有四个包
1.image放置图片包,
2.DataBase模拟银行系统中的账户信息,相当于数据库的功能,
3.frame放置了登入界面实现类与银行操作界面的实现类,运用了简单的GUI,实现了逻辑结构,
4.module放置用户模型类
还有一个properties文件,可以把数据读取到文件中

设计原理:
1.把银行用户放入到一个hashMap中,每次进入和退出程序,都会把hashMap表中的数据读取到properties文件中,达到保留数据的功能。
2.用户登入必须要输入对的userName与passWord才可以登入进去,bank界面可以实现存款,取款,查看余额,修改账户密码等等,都可以通过修改hashMap表中的数据来达到效果,然后再存入到properties文件中保留数据,保证下次登入时可以重新恢复数据

四、代码实现

>

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 
 * @date 2021/11/23 15:09
 * @details 模拟银行系统中的账户信息,相当于数据库的功能
 */
public class DataBaseUtil {
    private static DataBaseUtil instance = null;
    private static HashMap<String, User> users = new HashMap<>();

    private DataBaseUtil(){
        Properties pro =new Properties();//充当简单的数据库

        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);//加入到集合中

        }
        /*
        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(){//懒汉式单例模式,使所有对象唯一了
        if(instance == null){//同步代码块p371
            synchronized (DataBaseUtil.class){
                instance = new DataBaseUtil();
            }
        }
        return instance;
    }

    //根据id获得用户个人信息
    public static User getUser(String userName){
        return users.get(userName);
    }

    //获得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);
            //判断id与密码是否一致
            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
 * @date 2021/11/30 11:38
 * @details 简单实现银行面板,和一些基本操作(存钱,取钱,余额,修改密码)
 */
public class BankFrame extends JFrame {
    private User user;
    Properties pro = new Properties();//充当简单的数据库
    int index;//数据库索引
    JPanel contentPane;
    JScrollPane scp = new JScrollPane();
    JTable tab = null;
    String text;//文本数据
    Vector CellsVector = new Vector();// 标题行
    Vector TitleVector = new Vector();// 数据行
    JButton btn_save = new JButton("存钱");
    JButton btn_withdraw = new JButton("取钱");
    JButton btn_remain = new JButton("余额");
    JButton btn_set_passWord = new JButton("修改密码");

    JTextField text_context = new JTextField();//输入内容

    JLabel context = new JLabel("输入相关数字: ");

    public BankFrame(String userName){


        try {//加载数据库
            pro.load(new FileReader("src/data.properties"));
        } catch (
                IOException e) {
            e.printStackTrace();
        }
        index = getUserIndex(userName);
        //获得user对象
        user = DataBaseUtil.getUser(userName);
        //JPanel面板的设置
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(null);
        this.setResizable(false);
        setSize(new Dimension(600, 340));
        setLocationRelativeTo(null);
        setTitle(user.getUserName() + "用户");
        //滑动面板的设置
        scp.setBounds(new Rectangle(46, 32, 497, 157));
//        JLabel的坐标建立
        context.setFont(new Font("宋体", Font.BOLD, 14));
        context.setBounds(136,200,126,20);
        //Text的坐标建立
        text_context.setBounds(255,200,130,20);
        text_context.setFont(new Font("宋体", Font.BOLD, 14));
        text_context.setDocument(new JTextFieldLimit(12));//限制密码长度为12

        //Button的坐标建立
        btn_save.setBounds(new Rectangle(85, 271, 70, 25));
        btn_save.setFont(new Font("宋体", 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);//存入用户存款
                    DataBaseUtil.getUsers().put(user.getCardId(),user);//存入数据库
                    pro.setProperty(index+"-account",String.valueOf(user.getAccount()));
                    try {
                        pro.store(new FileWriter("src/data.properties"),"修改值");
                    } 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("存款");
                    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("宋体", 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()){//判断余额不足
                        JOptionPane.showMessageDialog(contentPane, "您好!你的账户余额不足!", "提示", 1);
                        text_context.setText("");
                        return;
                    }

                    user.setAccount(user.getAccount()-num);//存入用户存款
                    DataBaseUtil.getUsers().put(user.getCardId(),user);//存入数据库
                    pro.setProperty(index+"-account",String.valueOf(user.getAccount()));
                    try {//将properties加载到对应文件中
                        pro.store(new FileWriter("src/data.properties"),"修改值");
                    } 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("取款");
                    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("宋体", 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("账户余额");
                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("宋体", Font.BOLD, 12));
        btn_set_passWord.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //检查操作
                text = text_context.getText();
                if (text.equals("")) {//如果是空的输入,输入警告
                    JOptionPane.showMessageDialog(contentPane, "您好!请输入密码!", "提示", 1);
                    text_context.grabFocus();
                    return;
                }
                user.setCardPwd(text);//数据库修改密码
                DataBaseUtil.getUsers().put(user.getCardId(),user);
                JOptionPane.showMessageDialog(contentPane, "修改成功! 账户名:"+ user.getUserName() + " 密码:" +user.getCardPwd(), "提示", 1);
                pro.setProperty(index+"-pwd",String.valueOf(user.getCardPwd()));
                try {
                    pro.store(new FileWriter("src/data.properties"),"修改值");
                } 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("修改密码");
                vector.add("修改成功");
                vector.add(now.format(dtf));
                CellsVector.add(vector);
                tab.updateUI();
                text_context.setText("");
            }
        });

        //将组件添加到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("查询操作");
        this.TitleVector.add("操作数额(人民币元)");
        this.TitleVector.add("操作时间");

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


    // 对输入框进行验证
    public boolean checkInformation() {
        text = text_context.getText();

        if (text.equals("")) {//如果是空的输入,输入警告
            JOptionPane.showMessageDialog(contentPane, "您好!请输入数额!", "提示", 1);
            text_context.grabFocus();
            return false;
        }
        char[] ans = text.toCharArray();
        for (int i = 0; i < ans.length; i++) {//遍历每个字符
            if (!Character.isDigit(ans[i])) {//如果不是数字输出,输出警告
                JOptionPane.showMessageDialog(contentPane, "您好!数额只可以是数字!", "提示", 1);
                text_context.setText("");
                text_context.grabFocus();
                return false;
            }
            if (text.length() > 5) {
                JOptionPane.showMessageDialog(contentPane, "您好! 存款不可以超过99999元", "提示", 1);
                text_context.setText("");
                text_context.grabFocus();
                return false;
            }
        }
        text_context.setText("");
        return true;
    }

    //从Properties中获取对应的user
    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 
 * @date 2021/11/30 11:38
 * @details 登入界面的实现类
 */
public class LoginFrame extends JFrame {
    /**
     * 用户名
     */
    private static final JLabel usernameLabel = new JLabel("用户名(小于12位)");
    private static final JTextField usernameInput = new JTextField();

    /**
     * 密码
     */
    private static final JLabel passwordLabel = new JLabel("密码(小于12位)");
    private static final JTextField passwordInput = new JPasswordField();
    /**
     * 登录和退出按钮
     */
    private static final JButton loginButton = new JButton(new ImageIcon("image/login.png"));//使用图片
    //	private static final JButton loginButton = new JButton("登录");
    private static final JButton exitButton = new JButton("注册   ");




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



        // 设置窗体的标题
        setTitle("银行登入系统");
        setLayout(null);

        //初始化界面
        initUI();

        // 点击关闭退出程序
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // 设置窗体可见
        setVisible(true);

        //数据库的加载
        DataBaseUtil.getInstance();

        // 该处设计为登录按钮的监听
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 获取用户名和密码输入框的值
                String userName = usernameInput.getText().trim();
                String passWord = passwordInput.getText().trim();

                // 用户名为空时提示用户输入
                if ("".equals(userName)) {
                    //JOptionPane可以轻松地弹出一个标准对话框,
                    // 提示用户获取值或通知他们某些东西。
                    JOptionPane.showMessageDialog(LoginFrame.this, "请输入用户名");
                    return;
                }
                // 密码为空时提示用户输入
                if ("".equals(passWord)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "请输入密码");
                    return;
                }

                // 查询数据库
                if (!DataBaseUtil.CheckLogin(userName, passWord)) {
                    JOptionPane.showMessageDialog(LoginFrame.this, "用户名或密码错误");
                    return;
                }

                // 首先关闭当前界面
                dispose();
                // 打开用户管理界面
                new BankFrame(userName);
            }
        });

        // 该处设计为退出按钮的监听
        exitButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }


    /**
     * 初始化界面
     */
    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);
    }



    //启动入口
    public static void main(String[] args) {
        new LoginFrame();
    }

}


//限制输入长度的类
class   JTextFieldLimit extends PlainDocument {

    private int limit;  //限制的长度

    public JTextFieldLimit(int limit) {
        super(); //调用父类构造
        this.limit = limit;
    }
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if(str == null) return;

        //下面的判断条件改为自己想要限制的条件即可,这里为限制输入的长度
        if((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);//调用父类方法
        }
    }

}
package BankManagementSystem.model;

/**
 * @author 
 * @date 2021/11/23 15:01
 * @details 用户信息类
 */
public class User {
    private String cardId;//用户id
    private String cardPwd;//用户密码
    private String userName;//用户名
    private String callNum;//用户电话号码
    private int account;//用户账户余额

    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;
    }
}

还有一个data.properties文件不要忘了创建在src包下并且加入allNum=0这一行数据即可!

五、结果分析与总结

在这里插入图片描述
在这里插入图片描述

  • 6
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
### 回答1: 好的,以下是一个简单的Java+Swing模拟银行存取款业务的示例代码: ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Bank extends JFrame implements ActionListener { // 定义组件 JLabel label1, label2, label3; JTextField text1, text2, text3; JButton button1, button2; JPanel panel1, panel2, panel3; public Bank() { // 初始化组件 label1 = new JLabel("账户:"); label2 = new JLabel("密码:"); label3 = new JLabel("余额:"); text1 = new JTextField(10); text2 = new JTextField(10); text3 = new JTextField(10); text3.setEditable(false); button1 = new JButton("存款"); button2 = new JButton("取款"); panel1 = new JPanel(); panel2 = new JPanel(); panel3 = new JPanel(); // 设置布局 panel1.setLayout(new GridLayout(3, 1)); panel2.setLayout(new GridLayout(3, 1)); panel3.setLayout(new FlowLayout()); // 添加组件 panel1.add(label1); panel1.add(label2); panel1.add(label3); panel2.add(text1); panel2.add(text2); panel2.add(text3); panel3.add(button1); panel3.add(button2); // 添加事件监听器 button1.addActionListener(this); button2.addActionListener(this); // 将面板添加到窗体中 this.add(panel1, BorderLayout.WEST); this.add(panel2, BorderLayout.CENTER); this.add(panel3, BorderLayout.SOUTH); // 设置窗体属性 this.setTitle("银行存取款业务"); this.setSize(300, 150); this.setLocationRelativeTo(null); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { // 存款 double balance = Double.parseDouble(text3.getText()); double deposit = Double.parseDouble(text2.getText()); balance += deposit; text3.setText(String.valueOf(balance)); JOptionPane.showMessageDialog(this, "存款成功!"); } else if (e.getSource() == button2) { // 取款 double balance = Double.parseDouble(text3.getText()); double withdraw = Double.parseDouble(text2.getText()); if (withdraw > balance) { JOptionPane.showMessageDialog(this, "余额不足!"); } else { balance -= withdraw; text3.setText(String.valueOf(balance)); JOptionPane.showMessageDialog(this, "取款成功!"); } } } public static void main(String[] args) { new Bank(); } } ``` 这个示例代码创建了一个窗体,包含一个账户、密码、余额、存款和取款的输入框和按钮。当用户点击存款按钮时,程序会将输入的金额加到余额中,并弹出一个消息框提示存款成功;当用户点击取款按钮时,程序会检查余额是否足够,如果够就将输入的金额从余额中减掉,并弹出一个消息框提示取款成功。 ### 回答2: Java Swing是一个用于创建桌面应用程序的用户界面(UI)工具包。通过使用Java Swing,我们可以实现一个简单的银行存取款业务模拟程序。 首先,我们需要创建一个银行账户类,该类包含账户号码、账户余额和相关的方法,如存款和取款。使用Java Swing,我们可以创建一个界面,其中包含文本框和按钮,用于输入存取款金额和执行相关操作。 接下来,我们需要创建一个主类,用于处理界面事件和与银行账户类的交互。当用户点击存款按钮时,程序将获取输入的存款金额,并调用账户类中的存款方法来更新账户余额。同样,当用户点击取款按钮时,程序将获取输入的取款金额,并调用账户类中的取款方法来更新账户余额。 在界面上,我们可以显示账户当前的余额,并在每次执行存取款操作后更新余额的显示。 例如,在用户输入存款金额后,程序可以通过以下代码调用账户类的存款方法来更新余额: ``` double depositAmount = Double.parseDouble(depositTextField.getText()); account.deposit(depositAmount); balanceLabel.setText("账户余额:" + account.getBalance()); ``` 类似地,在用户输入取款金额后,程序可以通过以下代码调用账户类的取款方法来更新余额: ``` double withdrawAmount = Double.parseDouble(withdrawTextField.getText()); account.withdraw(withdrawAmount); balanceLabel.setText("账户余额:" + account.getBalance()); ``` 通过使用Java Swing,我们可以创建一个用户友好的界面来模拟银行存取款业务。用户可以输入存取款金额,并通过点击按钮来执行相关操作,同时实时显示账户余额的更新。这样,用户可以方便地进行模拟银行业务操作。 ### 回答3: Java Swing是Java提供的一组GUI(图形用户界面)工具包,可以用于开发桌面应用程序。对于模拟银行存取款业务,可以利用Java Swing创建一个银行存取款的界面,并在界面上提供相应的输入框和按钮。 首先,需要设计一个界面,包括一个账号输入框、一个金额输入框、一个存款按钮和一个取款按钮。当用户输入账号和金额后,点击存款按钮,程序会将相应的金额存入账号对应的余额中;当用户点击取款按钮,程序会从账号对应的余额中提取相应的金额。 其次,需要设计一个账户类,包含账号和余额两个属性,并提供相应的存款和取款方法。在存款方法中,会将存款金额与原有余额相加,得到新的余额;在取款方法中,会将取款金额与原有余额相减,得到新的余额。 最后,将界面与账户类进行关联。当用户点击存款按钮时,界面会获取账号和金额,并调用账户类的存款方法将金额存入账号对应的余额中;当用户点击取款按钮时,界面会获取账号和金额,并调用账户类的取款方法从账号对应的余额中提取相应的金额。 通过以上步骤,可以用Java Swing模拟银行存取款业务。用户可以在界面上输入账号和金额,并通过点击按钮的方式进行存款和取款操作。程序会根据用户的输入,更新账号对应的余额,并在界面上显示最新的余额信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值