小编最近在复习java基础,心血来潮学了下Swing(以前没学过),写了一个模拟ATM取款程序。
ATM模拟取款程序:
登录界面:
图片中小编还加入了一个 时间实时更新功能。
Login类(登录)
package swpu.edu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 功能描述: 登录界面
* @param:
* @return:
* @auther:
* @date:
*/
public class Login extends JFrame implements ActionListener{
private JPanel p1,p2,p3,p4; //界面元素对象
private JTextField username,userpassword;//接收界面账号、密码
private JButton login;//登录按钮
private Timer timer;//时间容器
private JLabel timelable;
public Login(){
//主界面
this.setTitle("ATM模拟");
this.setSize(500,300);
this.setLocation(500,200);//界面显示位置
this.setLayout(null);
this.setResizable(false);//界面不可缩放
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭界面,程序结束
//界面元素1:标题
p1=new JPanel();
p1.setBounds(140,30,200,30);//界面位置、大小
p1.setBackground(new Color(55,100,97));
this.add(p1);
p1.add(new JLabel("万氏银行"));
//界面元素2:账号
p2=new JPanel();
p2.setBounds(80,80,300,30);
this.add(p2);
p2.add(new JLabel("账号: "));
username=new JTextField(20);
p2.add(username);
//界面元素3:密码
p3=new JPanel();
p3.setBounds(80,120,300,30);
this.add(p3);
p3.add(new JLabel("密码: "));
userpassword=new JPasswordField(20);
p3.add(userpassword);
//界面元素4:登录按钮
login=new JButton("登录");
login.addActionListener(this);//触发监听事件,验证用户信息
p4=new JPanel();
p4.setBounds(90,160,300,30);
this.add(p4);
p4.add(login);
//时间显示
timelable=new JLabel("");
timelable.setBounds(300,220,200,30);
timer=new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
timelable.setText(new SimpleDateFormat("yyyy年MM月dd日:hh:mm:ss")
.format(new Date()));
}
});
timer.start();
this.add(timelable);
this.setVisible(true);//界面可见
}
//测试
public static void main(String[] args) {
new Login();
}
@Override
public void actionPerformed(ActionEvent e) {
new Account();//调用Account构造器,读取文件信息
System.out.println(username.getText().toString());
System.out.println(Account.userid);
if(username.getText().toString().equals(Account.userid)) {
if (userpassword.getText().toString().equals(Account.userpassword)) {
this.dispose();//释放当前界面资源,关闭当前界面
new Menu();
}
else if(userpassword.getText().toString().equals("")){
JOptionPane.showMessageDialog(this,"账户或密码不能为空");
}else{
JOptionPane.showMessageDialog(this,"密码错误");
}
}else if(username.getText().toString().equals("")){
JOptionPane.showMessageDialog(this,"账户或密码不能为空");
}else{
JOptionPane.showMessageDialog(this,"账户错误");
}
}
}
功能栏