21xrx.com
2024-09-20 06:07:26 Friday
登录
文章检索 我的文章 写文章
JAVAATM取款机:用Java实现的简单取款机模拟程序
2023-06-18 02:13:09 深夜i     --     --
Java编程 ATM机 Swing包

在现代生活中,ATM机已经变成了人们处理日常金融事务的重要工具之一。而对于那些对于编程感兴趣的人来说,也可以通过编写自己的ATM程序来了解和探索这方面的知识。本文将介绍如何使用Java语言来创建简单的取款机模拟程序。

首先,我们需要构建用户界面,包括输入框、按钮和标签等。在Java中,使用Swing包可以方便地实现这些功能。下面的代码段展示了如何创建一个简单的登录框。


import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class LoginFrame extends JFrame {

  JLabel userLabel, passLabel;

  JTextField userText;

  JPasswordField passText;

  JButton loginButton, exitButton;

  LoginFrame() {

   setTitle("Java ATM");

   setSize(300, 180);

   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   setLocationRelativeTo(null);

   setLayout(null);

   userLabel = new JLabel("帐号:");

   passLabel = new JLabel("密码:");

   userText = new JTextField(10);

   passText = new JPasswordField(10);

   loginButton = new JButton("登录");

   exitButton = new JButton("退出");

   userLabel.setBounds(60, 20, 50, 30);

   passLabel.setBounds(60, 60, 50, 30);

   userText.setBounds(100, 20, 120, 30);

   passText.setBounds(100, 60, 120, 30);

   loginButton.setBounds(60, 100, 80, 30);

   exitButton.setBounds(140, 100, 80, 30);

   add(userLabel);

   add(passLabel);

   add(userText);

   add(passText);

   add(loginButton);

   add(exitButton);

   setVisible(true);

  }

}

一旦用户输入帐号和密码,程序将验证用户名和密码是否匹配。如果匹配,则将启动ATM机程序并进入主菜单。如果不匹配,则将提示用户重新输入。


class ATM {

  public boolean authenticate(String username, String password)

    // TODO: 在此处增加代码

  public void run()

    // TODO: 在此处增加代码

}

class Main {

  public static void main(String[] args) {

    LoginFrame login = new LoginFrame();

    login.loginButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        String username = login.userText.getText();

        String password = new String(login.passText.getPassword());

        ATM atm = new ATM();

        if (atm.authenticate(username, password)) {

          // 登录成功,进入ATM机主程序

          atm.run();

        } else {

          // 用户名或密码错误,提示用户重新输入

          JOptionPane.showMessageDialog(null, "错误的用户名或密码");

          login.userText.setText("");

          login.passText.setText("");

        }

      }

    });

    login.exitButton.addActionListener(new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        System.exit(0);

      }

    });

  }

}

综上所述,我们已经学会了如何使用Java来创建简单的ATM机模拟程序。在这个过程中,我们使用了Swing包来构建用户界面,使用了JOptionPane类来显示错误消息,以及使用了事件监听器来处理用户输入。这些知识点都是Java编程中非常重要的部分。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复