Java swing ATM
时间: 2023-08-31 21:05:44 浏览: 160
Java Swing ATM是一个简单的ATM应用程序,使用Java Swing GUI库开发。它允许用户执行以下操作:
1. 登录账户
2. 查看账户余额
3. 存款
4. 取款
下面是一个简单的Java Swing ATM示例:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ATM extends JFrame implements ActionListener {
private JTextField txtUser;
private JPasswordField txtPass;
private JButton btnLogin, btnDeposit, btnWithdraw, btnBalance;
private JLabel lblStatus, lblAmount;
private double balance = 0;
public ATM() {
setTitle("ATM");
setSize(400, 250);
setLayout(new GridLayout(4, 2));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUser = new JLabel("User:");
add(lblUser);
txtUser = new JTextField();
add(txtUser);
JLabel lblPass = new JLabel("Password:");
add(lblPass);
txtPass = new JPasswordField();
add(txtPass);
btnLogin = new JButton("Login");
btnLogin.addActionListener(this);
add(btnLogin);
btnDeposit = new JButton("Deposit");
btnDeposit.addActionListener(this);
add(btnDeposit);
btnWithdraw = new JButton("Withdraw");
btnWithdraw.addActionListener(this);
add(btnWithdraw);
btnBalance = new JButton("Balance");
btnBalance.addActionListener(this);
add(btnBalance);
lblStatus = new JLabel("");
add(lblStatus);
lblAmount = new JLabel("");
add(lblAmount);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnLogin) {
String user = txtUser.getText();
String pass = new String(txtPass.getPassword());
if (user.equals("admin") && pass.equals("1234")) {
lblStatus.setText("Login successful.");
btnDeposit.setEnabled(true);
btnWithdraw.setEnabled(true);
btnBalance.setEnabled(true);
} else {
lblStatus.setText("Invalid username or password.");
btnDeposit.setEnabled(false);
btnWithdraw.setEnabled(false);
btnBalance.setEnabled(false);
}
} else if (e.getSource() == btnDeposit) {
String amount = JOptionPane.showInputDialog("Enter amount to deposit:");
double deposit = Double.parseDouble(amount);
balance += deposit;
lblAmount.setText("Balance: " + balance);
} else if (e.getSource() == btnWithdraw) {
String amount = JOptionPane.showInputDialog("Enter amount to withdraw:");
double withdraw = Double.parseDouble(amount);
if (withdraw > balance) {
lblStatus.setText("Insufficient funds.");
} else {
balance -= withdraw;
lblAmount.setText("Balance: " + balance);
}
} else if (e.getSource() == btnBalance) {
lblAmount.setText("Balance: " + balance);
}
}
public static void main(String[] args) {
ATM atm = new ATM();
atm.setVisible(true);
}
}
```
在该示例中,我们创建了一个带有文本框、密码框和按钮的窗体。用户可以输入用户名和密码并点击“登录”按钮来登录账户。如果登录成功,则用户可以点击“存款”、“取款”和“余额”按钮来执行相应的操作。存款和取款操作将弹出一个对话框,要求用户输入金额。账户余额将在标签中显示。
阅读全文