目录结构:

效果图:

源代码:

package Work;import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;/*******用户交易类*****/public class Atm extends JFrame {//         金额文本框   账号文本框JTextField moneyText, idText;//              密码框      新密码框       重复密码框JPasswordField pwdText, pwdNewFirText, pwdNewSecText;//       密码         新密码         重复密码          金额        账号       余额          标题        时间JLabel pwdLabel, pwdNewFirLabel, pwdNewSecLabel, moneyLabel, idLabel, accountLabel, titleLabel, timeLabel;//          确定           取消          登录          重登JButton submitButton, cancelButton, loginButton, restartButton;JScrollPane jScrollPane;MyTable myTable;ArrayList<JComponent> componentList = new ArrayList<>();//账户String id;//密码String password;//余额int account;//数据库DataBase data;//结果集ResultSet resultSet;//输入流Scanner sc = new Scanner(System.in);//获取结果集ArrayList<User> userList = new ArrayList<>();//获取记录ArrayList<Message> messageList = new ArrayList<>();public void setFrame(){//设置不可调节大小setResizable(false);//设置布局为空getContentPane().setLayout(null);}//登录与注册的构造方法public Atm(DataBase data, int choice){if(choice == 0){this.data = data;init();login();}else if(choice == 1){this.data = data;init();insertId();}}//其他功能构造public Atm(DataBase data, int choice, String idGet, String pwdGet) {this.id = idGet;this.password = pwdGet;this.data = data;init();switch (choice){case 1:save();break;case 2:draw();break;case 3:search();break;case 4:changeNew();break;case 5:close();break;case 6:send();break;case 7:Atm atm = new Atm(this.data, 0);break;case 8:Menu menu = new Menu(this.data);break;case 9:viewRecord();default:break;}}//初始化public void init(){try {this.resultSet = data.state.executeQuery("SELECT * FROM USER");while(this.resultSet.next()){User user = new User(resultSet.getString("id"), resultSet.getString("password"), Integer.parseInt(resultSet.getString("money")));userList.add(user);}} catch (SQLException E) {E.printStackTrace();}if(this.id != null){for (User user : userList) {if(user.getId().equals(this.id)){this.account = user.getAccount();}}}}//登录public void login() {//设置窗口的参数setBounds(500,300,600,400);//设置关闭setDefaultCloseOperation(EXIT_ON_CLOSE);//禁用重新调整窗口大小的功能setResizable(false);//设置窗口上当前程序的名字setTitle("JavaATM--登录页面");//清除默认的布局管理器getContentPane().setLayout(null);//设置窗口显示setVisible(true);//文本输入框(以及密码输入框)idText = new JTextField();pwdText = new JPasswordField();//设置位置(左上角坐标)与宽高idText.setBounds(200, 110, 200, 45);pwdText.setBounds(200, 175, 200, 45);//存入集合componentList.add(idText);componentList.add(pwdText);//放到页面上getContentPane().add(idText);getContentPane().add(pwdText);//标签idLabel = new JLabel("账号:");pwdLabel = new JLabel("密码:");titleLabel = new JLabel("ATM登录");timeLabel = new JLabel();//设置坐标与宽高idLabel.setBounds(130, 110, 60, 45);pwdLabel.setBounds(130, 175, 60, 45);titleLabel.setBounds(240, 50, 200, 60);timeLabel.setBounds(5, 320, 305, 40);//存入集合componentList.add(idLabel);componentList.add(pwdLabel);componentList.add(timeLabel);//titleLabel不存入集合单独设置titleLabel.setFont(new Font("黑体", Font.BOLD, 24));//放到页面上getContentPane().add(idLabel);getContentPane().add(pwdLabel);getContentPane().add(titleLabel);getContentPane().add(timeLabel);//按钮loginButton = new JButton("登录");restartButton = new JButton("重置");//设置大小loginButton.setBounds(210, 240, 80, 40);restartButton.setBounds(310, 240, 80, 40);//存入集合componentList.add(loginButton);componentList.add(restartButton);//放置于页面getContentPane().add(loginButton);getContentPane().add(restartButton);//整体设置字体for (JComponent jComponent : componentList) {jComponent.setFont(new Font("宋体", Font.BOLD, 20));}this.getRootPane().setDefaultButton(loginButton);loginButton.addActionListener(e -> {String idGet = idText.getText();String pwdGet = pwdText.getText();boolean flag = false;for (User user : userList) {if (user.getId().equals(idGet)) {if (user.getPwd().equals(pwdGet)) {try {recordMessage(idGet, "登录", "正常登录");AtmUi atmUi = new AtmUi(data, idGet, pwdGet);dispose();} catch (Exception E) {E.printStackTrace();}} else {JOptionPane.showMessageDialog(getContentPane(), "密码错误");}flag = true;break;}}if (!flag) {JOptionPane.showMessageDialog(getContentPane(), "账号错误");}});restartButton.addActionListener(e -> {idText.setText("");pwdText.setText("");});}//开户public void insertId() {//设置窗口的参数setBounds(500,300,600,400);//禁用重新调整窗口大小的功能setResizable(false);//设置窗口上当前程序的名字setTitle("JavaATM--开户页面");//清除默认的布局管理器getContentPane().setLayout(null);//设置窗口显示setVisible(true);idLabel = new JLabel("账号:");pwdNewFirLabel = new JLabel("密码:");pwdNewSecLabel = new JLabel("重复:");idText = new JTextField();pwdNewFirText = new JPasswordField();pwdNewSecText = new JPasswordField();submitButton = new JButton("确定");cancelButton = new JButton("取消");idLabel.setBounds(130, 50, 60, 45);pwdNewFirLabel.setBounds(130, 110, 60, 45);pwdNewSecLabel.setBounds(130, 170, 60, 45);idText.setBounds(200, 50, 240, 45);pwdNewFirText.setBounds(200, 110, 240, 45);pwdNewSecText.setBounds(200, 170, 240, 45);submitButton.setBounds(140, 250, 90, 50);cancelButton.setBounds(340, 250, 90, 50);componentList.add(idLabel);componentList.add(pwdNewFirLabel);componentList.add(pwdNewSecLabel);componentList.add(idText);componentList.add(pwdNewFirText);componentList.add(pwdNewSecText);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));add(jComponent);}this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String idGet = idText.getText(), pwdFir = pwdNewFirText.getText(), pwdSec = pwdNewSecText.getText();for (User user : userList) {if(user.getId().equals(idGet)){JOptionPane.showMessageDialog(getContentPane(), "账号重复");return;}}if(idTest(idGet)){if(pwdTest(pwdFir)){if(pwdFir.equals(pwdSec)){try {data.state.execute("INSERT INTO USER VALUES ('" + idGet + "', '" + pwdFir + "', 0)");recordMessage(id, "开户", "正常开户");JOptionPane.showMessageDialog(getContentPane(), "开户成功!跳转登录页面!");Atm atm = new Atm(data, 0);dispose();} catch (SQLException E) {E.printStackTrace();}}else {JOptionPane.showMessageDialog(getContentPane(), "密码不一致!");}}else {JOptionPane.showMessageDialog(getContentPane(), "密码安全性过低!");}}else {JOptionPane.showMessageDialog(getContentPane(), "账号不合法!");}}});}//存款public void save(){setFrame();//设置大小setBounds(600,300,360,200);//设置窗口名setTitle("存款");//设置显示setVisible(true);moneyLabel = new JLabel("金额:");moneyText = new JTextField();submitButton = new JButton("确定");cancelButton = new JButton("取消");moneyLabel.setBounds(10,20, 70, 50);moneyText.setBounds(80, 20, 250, 50);submitButton.setBounds(50, 90, 90, 50);cancelButton.setBounds(200, 90, 90, 50);componentList.add(moneyLabel);componentList.add(moneyText);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));}add(moneyLabel);add(moneyText);add(submitButton);add(cancelButton);this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//存款金额合法性验证(大于0并且是整百)if(moneyTest(moneyText.getText())){int money = Integer.parseInt(moneyText.getText());try {data.state.execute("UPDATE USER SET money = money + " + money + " WHERE id = '" + id + "'");account += money;recordMessage(id, "存款", "存款金额: " + money + ".00元");JOptionPane.showMessageDialog(getContentPane(), "存款成功!余额: " + account + ".00元");} catch (SQLException E) {E.printStackTrace();}}else{JOptionPane.showMessageDialog(getContentPane(), "存款金额大于0并且是整百!");}}});cancelButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(getContentPane(), "已经取消!");dispose();}});}/*** @param id 存款账号(转账)* @param moneyGet 存款金额(转账)* @return 返回该次存款是否成功。考虑条件包括:存款金额是否合法以及存款(转账)对象是否存在*///转账存款public boolean saveSend(String id,String moneyGet){int money = Integer.parseInt(moneyGet);//存款金额合法性验证(大于0并且是整百)if(money <= 0 || money % 100 !=0){return false;}try {this.data.state.execute("UPDATE USER SET money = money + " + money + " WHERE id = '" + id + "'");return true;} catch (SQLException e) {e.printStackTrace();}return false;}//取款public void draw(){setFrame();//设置大小setBounds(600,300,360,200);//设置窗口名setTitle("取款");//设置显示setVisible(true);moneyLabel = new JLabel("金额:");moneyText = new JTextField();submitButton = new JButton("确定");cancelButton = new JButton("取消");moneyLabel.setBounds(10,20, 70, 50);moneyText.setBounds(80, 20, 250, 50);submitButton.setBounds(50, 90, 90, 50);cancelButton.setBounds(200, 90, 90, 50);componentList.add(moneyLabel);componentList.add(moneyText);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));}add(moneyLabel);add(moneyText);add(submitButton);add(cancelButton);this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(e -> {//存款金额合法性验证(大于0并且是整百)if(moneyTest(moneyText.getText())){int money = Integer.parseInt(moneyText.getText());if(money <= account){try {data.state.execute("UPDATE USER SET money = money - " + money + " WHERE id = '" + id + "'");account -= money;recordMessage(id, "取款", "取款金额: " + money + ".00元");JOptionPane.showMessageDialog(getContentPane(), "取款成功!余额: " + account +".00元");} catch (SQLException E) {E.printStackTrace();}}}else{JOptionPane.showMessageDialog(getContentPane(), "取款金额大于0并且是整百并且大于余额!");}});cancelButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(getContentPane(), "已经取消!");dispose();}});}/*** @param moneyGet 取款金额(转账)* @return 返回该取款操作是否成功。考虑条件为取款金额是否合法*///转账取款public boolean drawSend(String moneyGet){if(moneyTest(moneyGet)){int money = Integer.parseInt(moneyGet);if(money <= account){try {data.state.execute("UPDATE USER SET money = money - " + money + " WHERE id = '" + id + "'");account -= money;recordMessage(id, "取款", "取款金额: " + money + ".00元");return true;} catch (SQLException E) {E.printStackTrace();}}}return false;}//查询public void search(){setFrame();//设置大小setBounds(600,300,360,240);//设置窗口名setTitle("查询");//设置显示setVisible(true);idLabel = new JLabel("账号: " + id);pwdLabel = new JLabel("密码: " + password);accountLabel = new JLabel("余额: " + account + ".00元");idLabel.setBounds(10, 20, 340, 50);pwdLabel.setBounds(10, 70, 340, 50);accountLabel.setBounds(10, 120, 340, 50);componentList.add(idLabel);componentList.add(pwdLabel);componentList.add(accountLabel);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));}add(idLabel);add(pwdLabel);add(accountLabel);}//修改public void changeNew(){setFrame();//设置大小setBounds(600,300,450,320);//设置窗口名setTitle("改密");//设置显示setVisible(true);pwdLabel = new JLabel("原始密码:");pwdNewFirLabel = new JLabel("新建密码:");pwdNewSecLabel = new JLabel("重复密码:");pwdText = new JPasswordField();pwdNewFirText = new JPasswordField();pwdNewSecText = new JPasswordField();pwdLabel.setBounds(10, 20, 120, 50);pwdNewFirLabel.setBounds(10, 80, 120, 50);pwdNewSecLabel.setBounds(10, 140, 120, 50);componentList.add(pwdLabel);componentList.add(pwdNewFirLabel);componentList.add(pwdNewSecLabel);pwdText.setBounds(130, 20, 260, 50);pwdNewFirText.setBounds(130, 80, 260, 50);pwdNewSecText.setBounds(130, 140, 260, 50);componentList.add(pwdText);componentList.add(pwdNewFirText);componentList.add(pwdNewSecText);submitButton = new JButton("确定");cancelButton = new JButton("取消");submitButton.setBounds(50, 210, 90, 50);cancelButton.setBounds(250, 210, 90, 50);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));add(jComponent);}this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String pwdOld = pwdText.getText(), pwdNewFir = pwdNewFirText.getText(), pwdNewSec = pwdNewSecText.getText();if (pwdOld.equals(password)) {if (pwdNewFir.equals(pwdNewSec) && pwdTest(pwdNewFir)) {try {data.state.execute("UPDATE USER SET password = '" + pwdNewFir + "' WHERE id = '" + id + "'");System.out.println("改密成功");System.out.println("========================");password = pwdNewFir;recordMessage(id, "改密", "正常修改密码");JOptionPane.showMessageDialog(getContentPane(), "成功!");dispose();Atm atm = new Atm(data, 0);} catch (SQLException E) {E.printStackTrace();}}}else {JOptionPane.showMessageDialog(getContentPane(), "密码错误或者不一致或者安全性太低!");}}});cancelButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(getContentPane(), "已经取消!");dispose();}});}//销户public void close(){setFrame();//设置大小setBounds(600,300,360,200);//设置窗口名setTitle("销户");//设置显示setVisible(true);pwdLabel = new JLabel("密码:");pwdText = new JPasswordField();submitButton = new JButton("确定");cancelButton = new JButton("取消");pwdLabel.setBounds(10,20, 70, 50);pwdText.setBounds(80, 20, 250, 50);submitButton.setBounds(50, 90, 90, 50);cancelButton.setBounds(200, 90, 90, 50);componentList.add(pwdLabel);componentList.add(pwdText);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));add(jComponent);}this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String pwdOld = pwdText.getText();if (pwdOld.equals(password)) {try {data.state.execute("DELETE FROM USER WHERE id = '" + id + "'");recordMessage(id, "销户", "正常销户,余额已取");JOptionPane.showMessageDialog(getContentPane(), "已经销户!余额: " + account + ".00元\n即将跳转登录页面");dispose();Menu menu = new Menu(data);} catch (SQLException E) {E.printStackTrace();}}else {JOptionPane.showMessageDialog(getContentPane(), "密码错误!");}}});cancelButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(getContentPane(), "已经取消!");dispose();}});}/***转账函数的查询有问题***///转账public void send(){setFrame();//设置大小setBounds(600,300,360,260);//设置窗口名setTitle("转账");//设置显示setVisible(true);idLabel = new JLabel("账号:");idText = new JTextField();moneyLabel = new JLabel("金额:");moneyText = new JTextField();submitButton = new JButton("确定");cancelButton = new JButton("取消");idLabel.setBounds(10,20, 70, 50);idText.setBounds(80, 20, 250, 50);moneyLabel.setBounds(10, 80, 70, 50);moneyText.setBounds(80, 80, 250, 50);submitButton.setBounds(50, 150, 90, 50);cancelButton.setBounds(200, 150, 90, 50);componentList.add(idLabel);componentList.add(idText);componentList.add(moneyLabel);componentList.add(moneyText);componentList.add(submitButton);componentList.add(cancelButton);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));add(jComponent);}this.getRootPane().setDefaultButton(submitButton);submitButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {String idGet = idText.getText();String money = moneyText.getText();//不能转给自己if(id.equals(idGet)){JOptionPane.showMessageDialog(getContentPane(), "不能转给自己!");dispose();return;}//转账账户存在性检测boolean flag = false;for (User user : userList) {if(user.getId().equals(idGet)){flag = true;break;}}//转账对象不存在if(!flag){JOptionPane.showMessageDialog(getContentPane(), "转账对象不存在!");dispose();return;}//转账就是一个取款一个存款,先取,能取成功才可能存成功if(drawSend(money)) {saveSend(idGet, money);int moneyGet = Integer.parseInt(money);account -= moneyGet;recordMessage(id, "转出", "转至 -> " + idGet + "; 转出金额: " + moneyGet + ".00元");recordMessage(idGet, "转入", "转自 -> " + id + "; 转入金额: " + moneyGet + ".00元");JOptionPane.showMessageDialog(getContentPane(), "转账成功!");}else {JOptionPane.showMessageDialog(getContentPane(), "转账金额不合法!");}}});cancelButton.addActionListener(e -> {JOptionPane.showMessageDialog(getContentPane(), "已经取消!");dispose();});}/*** @param id 账号* @return 返回该账号是否合法*///账号合法性和密码合法性检测功能封装public boolean idTest(String id){//长度检测(长度8-10)if(id.length() < 8 || id.length() > 10){//System.out.println("长度不符");return false;}char[] chars = id.toCharArray();//字符类型检测(只能是数字)for(Character c:chars){if(c <48 || c > 57){//System.out.println("请使用纯数字");return false;}}return true;}/*** @param pwd 密码* @return 返回该密码是否合法*/public boolean pwdTest(String pwd){//长度检测(只能是8位)if(pwd.length()!=8){//System.out.println("长度不符");return false;}char[] chars = pwd.toCharArray();int length = chars.length;//字符类型检测(只能是数字)for(Character c:chars){if(c < 48 || c > 57){//System.out.println("请使用纯数字");return false;}}//简易性测试//一个字符组成for(int i=0;i<length-1;i++){if(chars[i] == chars[i + 1] && i == length - 2){//System.out.println("密码不得只有一种字符");return false;}else if(chars[i] != chars[i + 1]){break;}}//等差数列for(int i=0;i<length-2;i++){int temp1 = chars[i] - chars[i + 1], temp2 = chars[i + 1] - chars[i + 2];if(temp1 == temp2 && i == length - 3){//System.out.println("密码不得是等差数列");return false;}else if(temp1 == temp2){break;}}return true;}public boolean moneyTest(String money){if (money.equals("")){return false;}char[] chars = money.toCharArray();for (char aChar : chars) {if(aChar < 48 || aChar > 57){return false;}}int price = Integer.parseInt(money);if(price >= 0 && price % 100 ==0){return true;}else{return false;}}/************************************************//***以下两个方法未启用***///清空数据public void deleteData(){try {this.data.state.execute("DELETE FROM USER");this.data.state.execute("DELETE FROM MESSAGE");System.out.println("清空成功");System.out.println("========================");return;} catch (SQLException e) {e.printStackTrace();}}//创建demo数据public void createDemoData(){try {String str = String.valueOf(Calendar.getInstance().getTime());this.data.state.execute("DELETE FROM USER");this.data.state.execute("DELETE FROM MESSAGE");this.data.state.execute("INSERT INTO USER VALUES ('11111111', '12121212', 0), ('22222222', '23232323', 10000), ('33333333', '34343434', 100000000)");this.data.state.execute("INSERT INTO MESSAGE VALUES ('11111111', '开户', '" + str + "', 'demo')");this.data.state.execute("INSERT INTO MESSAGE VALUES ('22222222', '开户', '" + str + "', 'demo')");this.data.state.execute("INSERT INTO MESSAGE VALUES ('33333333', '开户', '" + str + "', 'demo')");} catch (SQLException e) {e.printStackTrace();}}/************************************************///将时间格式更新为为符合中国人习惯的格式//记录private void recordMessage(String userId, String type, String info){try {/*  原格式例:Mon Jun 21 20:37:51 CST 2021String str = String.valueOf(Calendar.getInstance().getTime());*//**新格式**/StringBuffer sBuffer = new StringBuffer();//时分秒Calendar cal = Calendar.getInstance();int year = cal.get(Calendar.YEAR);//这样获取的月份是从0开始的int month = cal.get(Calendar.MONTH) + 1;int day = cal.get(Calendar.DAY_OF_MONTH);int hour = cal.get(Calendar.HOUR_OF_DAY);int minute = cal.get(Calendar.MINUTE);int second = cal.get(Calendar.SECOND);sBuffer.append(String.format("%04d", year)).append("年").append(month).append("月").append(day).append("日 ").append(String.format("%02d", hour)).append(":").append(String.format("%02d", minute)).append(":").append(String.format("%02d", second));String str = sBuffer.toString();/**新格式**/this.data.state.execute("INSERT INTO MESSAGE VALUES ('" + userId + "', '" + type + "', '" + str + "', '" + info + "')");Message message = new Message(userId, type, str, info);messageList.add(message);} catch (SQLException e) {e.printStackTrace();}}//查看记录private void viewRecord(){setFrame();//设置大小setBounds(600,300,1050,600);//设置窗口名setTitle("流水记录");//设置显示setVisible(true);myTable = new MyTable(this.data, this.id);jScrollPane = new JScrollPane(myTable);jScrollPane.setBounds(10, 10, 1000, 520);add(jScrollPane);}}
package Work;/**atm的图形化界面**/import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;public class AtmUi extends JFrame implements ActionListener {//      标题          时间         下划线JLabel titleLabel, timeLabel, lineLabel;//           存款            取款            查询          改密JButton moneyInButton, moneyOutButton, searchButton, updateButton,//          销户        转账         重登           退出         记录killButton, sendButton, reLoginButton, exitButton, infoButton;//控件集合ArrayList<JComponent> componentList = new ArrayList<>();Timer timer;Atm atm;DataBase dataBase;String id, pwd;public AtmUi(DataBase dataBase, String idGet, String pwdGet) throws Exception {this.dataBase = dataBase;this.id = idGet;this.pwd = pwdGet;//放置控件,设置面板setComponent();mainFrame();//定时器timer = new Timer(0, E -> {StringBuffer sBuffer = new StringBuffer();
//时分秒Calendar cal = Calendar.getInstance();int year = cal.get(Calendar.YEAR);//这样获取的月份是从0开始的int month = cal.get(Calendar.MONTH) + 1;int day = cal.get(Calendar.DAY_OF_MONTH);int hour = cal.get(Calendar.HOUR_OF_DAY);int minute = cal.get(Calendar.MINUTE);int second = cal.get(Calendar.SECOND);sBuffer.append(String.format("%04d", year)).append("年").append(month).append("月").append(day).append("日 ").append(String.format("%02d", hour)).append(":").append(String.format("%02d", minute)).append(":").append(String.format("%02d", second));timeLabel.setText(sBuffer.toString());});timer.start();}//面板设置方法public void mainFrame(){//设置大小setBounds(400,200,800,600);//设置关闭setDefaultCloseOperation(EXIT_ON_CLOSE);//设置不可调节大小setResizable(false);//设置窗口名setTitle("Atm业务界面");//设置布局为空getContentPane().setLayout(null);//设置显示setVisible(true);}//控件设置方法public void setComponent(){timeLabel = new JLabel("timeLabel");titleLabel = new JLabel("欢迎使用JavaATM");String str = "-----------------------------------------------------";lineLabel = new JLabel(str);componentList.add(timeLabel);componentList.add(titleLabel);componentList.add(lineLabel);titleLabel.setBounds(270, 70, 280, 60);timeLabel.setBounds(10, 515, 480, 40);lineLabel.setBounds(0, 510, 840, 10);moneyInButton = new JButton("存款");moneyOutButton = new JButton("取款");searchButton = new JButton("查询");updateButton = new JButton("改密");sendButton = new JButton("转账");killButton = new JButton("销户");reLoginButton = new JButton("重登");exitButton = new JButton("退出");infoButton = new JButton("记录");componentList.add(moneyInButton);componentList.add(moneyOutButton);componentList.add(searchButton);componentList.add(updateButton);componentList.add(sendButton);componentList.add(killButton);componentList.add(reLoginButton);componentList.add(exitButton);componentList.add(infoButton);moneyInButton.setBounds(120, 150, 100, 50);moneyOutButton.setBounds(570, 150, 100, 50);searchButton.setBounds(120, 240, 100, 50);updateButton.setBounds(570, 240, 100, 50);sendButton.setBounds(120, 330, 100, 50);killButton.setBounds(570, 330, 100, 50);reLoginButton.setBounds(120, 420, 100, 50);exitButton.setBounds(570, 420, 100, 50);infoButton.setBounds(570, 500, 100, 50);//事件监听moneyInButton.addActionListener(this);moneyOutButton.addActionListener(this);searchButton.addActionListener(this);updateButton.addActionListener(this);sendButton.addActionListener(this);killButton.addActionListener(this);reLoginButton.addActionListener(this);exitButton.addActionListener(this);infoButton.addActionListener(this);//给控件设置字体并且添加到面板for (JComponent jComponent : componentList) {jComponent.setFont(new Font("黑体", Font.BOLD, 30));add(jComponent);}}//事件监听@Overridepublic void actionPerformed(ActionEvent e) {if(e.getSource() == moneyInButton){atm = new Atm(this.dataBase, 1, this.id, this.pwd);}else if (e.getSource() == moneyOutButton){atm = new Atm(this.dataBase, 2, this.id, this.pwd);}else if (e.getSource() == searchButton){atm = new Atm(this.dataBase, 3, this.id, this.pwd);}else if (e.getSource() == updateButton){atm = new Atm(this.dataBase, 4, this.id, this.pwd);dispose();}else if (e.getSource() == sendButton){atm = new Atm(this.dataBase, 6, this.id, this.pwd);}else if (e.getSource() == killButton){atm = new Atm(this.dataBase, 5, this.id, this.pwd);dispose();}else if (e.getSource() == reLoginButton){atm = new Atm(this.dataBase, 7, this.id, this.pwd);dispose();}else if (e.getSource() == exitButton){atm = new Atm(this.dataBase, 8, this.id, this.pwd);dispose();}else if (e.getSource() == infoButton){atm = new Atm(this.dataBase, 9, this.id, this.pwd);}}
}
package Work;
/*
* 数据库创建:(自动创建)
* 表1:user
*       id char(10)
*       password char(10)
*       money int
*
* 表2:message
*       userId char(10)
*       type char(10)
*       time char(255)
*       info char(255)
* */
import java.sql.*;
import java.util.ArrayList;public class DataBase {private String path;//数据库地址及设置private String id;//数据库账号private  String password;//数据库密码public Connection con;//连接对象public Statement state;//执行对象public DataBase(String path, String id, String password) {//1.导入jar包,在项目内创建libs目录,将jar包复制到libs目录下//在idea内右键libs目录选择 Add As Library//注册数据库驱动try {Class.forName("com.mysql.cj.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}this.path = path;this.id = id;this.password = password;dataBase();String[] strBase = {"CREATE DATABASE if not exists AtmData DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;","use AtmData","CREATE TABLE if not exists user (id varchar(20), password varchar(20), money int);","CREATE TABLE if not exists message (userId VARCHAR(20), type varchar(30), time varchar(30), info varchar(255));"};for (String s : strBase) {try {this.state.execute(s);} catch (SQLException e) {e.printStackTrace();}}}//创建连接对象和执行对象private void dataBase() {//获取连接对象try {this.con = DriverManager.getConnection( this.path, this.id, this.password);//获取执行对象this.state = this.con.createStatement();} catch (Exception e) {e.printStackTrace();}}public ArrayList<Message> getMessageList(String idGet){ArrayList<Message> messageList = new ArrayList<>();try {ResultSet resultSet = this.state.executeQuery("select * from message");while(resultSet.next()){if(resultSet.getString("userId").equals(idGet)){Message message = new Message(resultSet.getString("userId"), resultSet.getString("type"), resultSet.getString("time"), resultSet.getString("info"));messageList.add(message);}}return messageList;} catch (SQLException e) {e.printStackTrace();}return messageList;}}
package Work;import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;/**帮助信息类**/
/*
* 创建记事本文件,提供帮助信息.
* */
public class HelpInformation {public HelpInformation() {init();}String helpInfo = "-----------------------帮助文档由此处开始----------------------------------------------------------------------------" +"\n\n1.本程序所有的金额输入只能是 纯阿拉伯数字, 且是100的整数倍\n" +"  , 大于0, 取款是需小于余额, 不得超过10000000000(包括单次金额和总存款)。\n" +"2.本程序创建的账号只能是 纯阿拉伯数字, 长度为[8,10]。\n" +"3.本程序创建的密码只能是 纯阿拉伯数字, 长度固定为8位。\n" +"4.本程序的作者为: Karry Song.\n" +"5.作者的CSDN: 'https://blog.csdn.net/may10?spm=1001.2101.3001.5343' .\n\n" +"重点: 任何不按照此帮助文档操作的行为导致程序出现异常都不是bug,无我无瓜。\n" +"本程序的使用需要在MySQL数据库下创建一个名为 'atmdata' 的数据库(大小写不敏感), 默认本地地址与3306端口号, 账号密码都是 'root'.\n" +"表格无需创建,自动创建,重启程序自动检测数据库以及表格是否存在。\n" +"若程序出现不可逆破坏,只需要删除数据库内容即可。提供两句SQL语句用于删除数据:'DELETE FROM message', 'DELETE FROM user'.\n\n" +"-----------------------帮助文档到此结束-----------------------------------------------------------------------------";String dirPath = "HelpInformation";String filePath = "HelpInformation\\helpTxt.txt";File dirFile = new File(dirPath);File txtFile = new File(filePath);FileWriter fw;BufferedWriter bw;public void init(){//为防止信息遭到破坏,每次重新创建文档if(dirFile.exists()){dirFile.delete();}dirFile.mkdir();if(txtFile.exists()){txtFile.delete();}try {txtFile.createNewFile();} catch (IOException e) {e.printStackTrace();}try {fw = new FileWriter(txtFile);} catch (IOException e) {e.printStackTrace();}bw = new BufferedWriter(fw);try {bw.write(helpInfo);bw.flush();bw.close();} catch (IOException e) {e.printStackTrace();}}}
package Work;public class Main {public static void main(String[] args) {//数据库地址String str = "jdbc:mysql://localhost:3306/atmData?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";String id = "root";String password = "root";//帮助文档HelpInformation helpInformation = new HelpInformation();DataBase dataBase = new DataBase(str, id, password);new Menu(dataBase);}
}
package Work;/***初始页面***/import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;public class Menu extends JFrame {DataBase dataBase;Atm atm;JButton loginButton, insertButton;JLabel titleLabel, timeLabel, authorLabel, urlLabel, helpLabel;ArrayList<JComponent> componentList = new ArrayList<>();Timer timer;public Menu(DataBase dataBase) {this.dataBase = dataBase;init();}public void init(){setComponent();setActionListen();setFrame();timer = new Timer(0, E -> {StringBuffer sBuffer = new StringBuffer();//时分秒Calendar cal = Calendar.getInstance();int year = cal.get(Calendar.YEAR);//这样获取的月份是从0开始的int month = cal.get(Calendar.MONTH) + 1;int day = cal.get(Calendar.DAY_OF_MONTH);int hour = cal.get(Calendar.HOUR_OF_DAY);int minute = cal.get(Calendar.MINUTE);int second = cal.get(Calendar.SECOND);sBuffer.append(String.format("%04d", year)).append("年").append(month).append("月").append(day).append("日 ").append(String.format("%02d", hour)).append(":").append(String.format("%02d", minute)).append(":").append(String.format("%02d", second));timeLabel.setText(sBuffer.toString());});timer.start();}public void setFrame(){//设置不可调节大小setResizable(false);//设置关闭setDefaultCloseOperation(EXIT_ON_CLOSE);//设置布局为空getContentPane().setLayout(null);//设置大小setBounds(600,300,600,400);//设置窗口名setTitle("登录页面");//设置显示setVisible(true);}public void setComponent(){loginButton = new JButton("登录");insertButton = new JButton("注册");titleLabel = new JLabel("欢迎使用JavaATM");timeLabel = new JLabel();authorLabel = new JLabel("作者: Karry Song ");urlLabel = new JLabel("CSDN: https://blog.csdn.net/may10?spm=1001.2101.3001.5343");helpLabel = new JLabel("请查看jar同级目录下的'HelpInformation'目录'HelpTxt.txt'帮助文档");titleLabel.setBounds(140, 20, 340, 80);loginButton.setBounds(130, 120, 90, 50);insertButton.setBounds(350, 120, 90, 50);timeLabel.setBounds(10, 310, 450, 50);authorLabel.setBounds(190, 180, 400, 80);urlLabel.setBounds(10, 220, 570, 80);helpLabel.setBounds(15, 250, 570, 80);componentList.add(timeLabel);componentList.add(titleLabel);componentList.add(loginButton);componentList.add(insertButton);componentList.add(authorLabel);componentList.add(urlLabel);componentList.add(helpLabel);for (JComponent jComponent : componentList) {jComponent.setFont(new Font("微软雅黑", Font.PLAIN, 24));add(jComponent);}titleLabel.setFont(new Font("黑体", Font.BOLD, 35));urlLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));helpLabel.setFont(new Font("微软雅黑", Font.PLAIN, 18));}//登录public void setActionListen(){loginButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {atm = new Atm(dataBase, 0);dispose();}});//注册insertButton.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {atm = new Atm(dataBase, 1);dispose();}});}}
package Work;/******记录信息类*****/public class Message {private String userId;private String type;private String time;private String info;public Message(String userId, String type, String time, String info) {this.userId = userId;this.type = type;this.time = time;this.info = info;}public Message() {}public String getUserId() {return userId;}public void setUserId(String userId) {this.userId = userId;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getTime() {return time;}public void setTime(String time) {this.time = time;}public String getInfo() {return info;}public void setInfo(String info) {this.info = info;}@Overridepublic String toString() {return "Message{" +", userId='" + userId + '\'' +", type='" + type + '\'' +", time='" + time + '\'' +", info='" + info + '\'' +'}';}
}
package Work;/**继承jtable**/import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.util.Enumeration;public class MyTable extends JTable{DataBase dataBase;String idGet;public MyTable(DataBase dataBase, String idGet) {this.dataBase = dataBase;this.idGet = idGet;TableModel tableModel = new TableModel(this.dataBase, this.idGet);//表头字体设置getTableHeader().setFont(new Font("黑体", Font.BOLD, 22));getTableHeader().setForeground(Color.RED);//表格字体设置setFont(new Font("微软雅黑", Font.PLAIN, 20));setForeground(Color.BLACK);//线条设置setGridColor(Color.BLACK);//表格宽度设置setRowHeight(50);//表格大小设置setBounds(200, 60, 800, 620);//多行选择设置getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//表头进制移动设置getTableHeader().setReorderingAllowed(false);setModel(tableModel);setTableStyle();}public void setTableStyle() {//设置选中行的背景色setSelectionBackground(new Color(224, 242, 255));//设置表格每行的高度setRowHeight(35);// 设置点击表头自动实现排序setAutoCreateRowSorter(false);// 设置表头文字居中显示DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) getTableHeader().getDefaultRenderer();renderer.setHorizontalAlignment(renderer.CENTER);// 设置表格中的数据居中显示DefaultTableCellRenderer r=new DefaultTableCellRenderer();r.setHorizontalAlignment(JLabel.CENTER);setDefaultRenderer(Object.class,r);setFocusable(false);setFont(new Font("新宋体", Font.PLAIN, 18));fitTableColumns(this);}// 根据内容自动调节表格的列宽度@SuppressWarnings("rawtypes")private static void fitTableColumns(JTable myTable){myTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);JTableHeader header = myTable.getTableHeader();int rowCount = myTable.getRowCount();Enumeration columns = myTable.getColumnModel().getColumns();while(columns.hasMoreElements()){TableColumn column = (TableColumn)columns.nextElement();int col = header.getColumnModel().getColumnIndex(column.getIdentifier());int width = (int)header.getDefaultRenderer().getTableCellRendererComponent(myTable, column.getIdentifier(), false, false, -1, col).getPreferredSize().getWidth();for(int row = 0; row < rowCount; row++){int preferedWidth = (int)myTable.getCellRenderer(row, col).getTableCellRendererComponent(myTable, myTable.getValueAt(row, col), false, false, row, col).getPreferredSize().getWidth();width = Math.max(width, preferedWidth);}header.setResizingColumn(column); // 此行很重要column.setWidth(width+myTable.getIntercellSpacing().width);}}}
package Work;import javax.swing.table.AbstractTableModel;
import java.util.*;//表格模板类public class TableModel extends AbstractTableModel {ArrayList<Object> colList = new ArrayList<>();ArrayList<Message> rowList;DataBase dataBase;ArrayList<Message> SQLData;Object[] tableCol = new Object[]{"userId", "type", "time", "info"};//空参构造,demo数据public TableModel(DataBase dataBase, String idGet) {this.dataBase = dataBase;SQLData = dataBase.getMessageList(idGet);//导入字段colList.addAll(Arrays.asList(tableCol));//导入行数据rowList = new ArrayList<>(SQLData);for (Message message : rowList) {System.out.println(message);}}@Overridepublic int getRowCount() {return rowList.size();}@Overridepublic int getColumnCount() {return colList.size();}@Overridepublic String getColumnName(int columnIndex) {return (String)colList.get(columnIndex);}//禁止直接在方格内修改数据@Overridepublic boolean isCellEditable(int row,int col) {return false;}@Overridepublic Object getValueAt(int rowIndex, int columnIndex) {if(columnIndex == 0){return rowList.get(rowIndex).getUserId();}else if(columnIndex == 1){return rowList.get(rowIndex).getType();}else if(columnIndex == 2){return rowList.get(rowIndex).getTime();}else if(columnIndex == 3){return rowList.get(rowIndex).getInfo();}return null;}public ArrayList<Object> getColList(){return colList;}public Object[] getColArray(){return tableCol;}}
package Work;/*****无效类*****/
/*******用户类*****/public class User {//用户属性//账户private String id;//密码private String pwd;//余额private int account;public User() {this.account = 0;}public User(String id, String pwd, int money) {this.id = id;this.pwd = pwd;this.account = money;}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public int getAccount() {return account;}public void setAccount(int account) {this.account = (Math.max(account, 0));}@Overridepublic String toString() {return "User{" +"id='" + id + '\'' +", pwd='" + pwd + '\'' +", money=" + account;}
}

TestJava,TestUi两个文件是测试文件,不需要。

程序提供帮助文档:

项目源程序:

链接:https://pan.baidu.com/s/19F0dZaOkVLdFY-qSICMqyQ 
提取码:9t6a

jar包已经打好,就在

javaSwing ATM相关推荐

  1. 基于JavaSwing ATM取款机系统的设计和实现

    本项目演示地址链接  > 前言: 本项目是使用Java swing开发,可实现ATM系统/银行系统的基本登陆.转账.查询余额.存取款业务.界面设计比较简介.适合作为Java课设设计以及学习技术使 ...

  2. 基于JavaSwing+mysql的图书管理系统设计和实现

    前言: 项目是使用Java swing开发,可实现基础数据维护.图书类型管理和维护.图书信息管理和维护.注销退出.关于作者简介等功能.界面设计比较简介.适合作为Java课设设计以及学习技术使用. 引言 ...

  3. 基于JavaSwing坦克大战游戏的设计和实现

     还记得传说中的经典90坦克大战吗?那些怀旧的记忆,伴随着我们一起走过来的经典坦克大战,刚开始那战战兢兢,屡屡被敌人坦克击毁的情景历历在目.现在好了,再也不用担心敌人坦克了,可以横冲直撞,横扫敌人坦克 ...

  4. 基于JavaSwing+Mysql的仓库管理系统设计和实现

    前言:           本项目是使用Java swing开发,可实现仓库管理系统登陆/注册/重置.登录后可以进行系统管理.原料管理.成品管理.管理记录以及注销退出等几大模块.界面设计比较简介.适合 ...

  5. Java Swing专栏订阅须知《必读》

     订阅前请先花2分钟阅读一下本篇文章 作者介绍 Hello 我是奥斯卡.CSDN Java领域优质创作者.潜力新星.原力计划周榜前三作者 全网粉丝4W+.阅读超百W.希望大家关注指导小奥.一起进步 专 ...

  6. Eclipse+Java+Swing+Mysql实现自助存取款机(ATM)系统

    目录 一.系统介绍 1.开发环境 2.技术选型 3.系统功能 4.数据库 5.工程截图 二.系统展示 1.注册页面 2.登录页面 3.主页面 4.取款 5.存款 6.转账 7.余额查询 三.部分代码 ...

  7. Python学习day5作业-ATM和购物商城

    Python学习day5作业 Python学习day5作业 ATM和购物商城 作业需求 ATM: 指定最大透支额度 可取款 定期还款(每月指定日期还款,如15号) 可存款 定期出账单 支持多用户登陆, ...

  8. Python ATM

    # ATM 模拟实现# 功能:# 输入对应的数字进入不同的功能:# 1. 支持进入商城购物,并通过信用卡结账.# 2. 支持信用卡余额查询.# 3. 支持不同用户之间的转账.# 4. 支持账单还款(充 ...

  9. ATM高层定义了4类业务,压缩视频信号的传送属于______。B

    ATM高层定义了4类业务,压缩视频信号的传送属于______.B A.CBR B.VBR C.UBR D.ABR [分析] ATM高层定义了如下4类业务: 固定比特率(CBR)业务,用于模拟铜线和光纤 ...

最新文章

  1. 技术17期:近几年崛起的Pytorch究竟是何方神圣?
  2. 关于numpy中eye和identity的区别详解
  3. 【转】android是32-bit系统还是64-bit系统
  4. IBM:决胜量子计算五大战略!商用近在咫尺
  5. java反射克隆对象_Java反射 - 2(对象复制,父类域,内省)
  6. 独立式环境与宿主式环境————《标准C语言指南》读书笔记01
  7. Java黑皮书课后题第10章:*10.5(显示素数因子)编写一个程序,提示用户输入一个正整数,然后以降序显示它的所有最小因子
  8. php ucword,ThinkPHP3.1.2整合UCenter详解(二)
  9. 还要我带一个六级辅导班--痛苦!
  10. 数据库健康状况监视_监视数据库运行状况和行为:哪些指标重要?
  11. Java讲课笔记22:Set接口及其实现类
  12. elementui 嵌套表单验证_elementUI 表单嵌套表格验证,日期选择器联动限制等写法
  13. Python破解百度翻js代码
  14. 终于,我们这代程序员在上海各奔东西
  15. pl/sql远程连接oracle总结
  16. ideal pom文件安装到maven库中_不装 maven 直接使用 IntelliJ 的插件来把本地 jar 包加入到 maven 仓库...
  17. springcloud之eureka集群搭建
  18. 怎样在计算机上安装计算器,如何在win10系统电脑上重新安装计算器
  19. 计算机网络专业怎么厉害,面试自我介绍:计算机网络专业
  20. java中System类详解

热门文章

  1. C#生成word压缩下载
  2. 大数据工程师、BI工程师、数据库工程师什么区别?
  3. allegro使用汇总
  4. 车载网络与计算机网络有什么不同,浅谈汽车车载网络的应用
  5. 初学者 深度学习 人工神经网络 可视化网站
  6. 新型肺炎疫情导致华为手机遭受重大挫折,排名滑落两名
  7. Dharma家族变体,.adobe后缀勒索病毒解密
  8. 腾讯“立知”被疑抄袭“即刻”
  9. 大屏监控系统实战(6)-爬虫初探:爬取CSDN博客之星年度总评选投票统计数据
  10. 长沙一佳一教育科技有限公司:短视频如何制作