Java+Swing模拟银行存取款业务(要求存取款功能以及余额查询功能)
时间: 2023-12-20 22:03:41 浏览: 82
基于Java语言实现模拟银行存取款业务系统
5星 · 资源好评率100%
下面是一个简单的Java+Swing模拟银行存取款业务的示例代码,包含存取款功能以及余额查询功能。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class BankApp extends JFrame implements ActionListener {
private JLabel balanceLabel;
private JTextField amountField;
private JButton depositButton, withdrawButton, balanceButton;
private double balance = 0;
public BankApp() {
setTitle("Bank App");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 150);
balanceLabel = new JLabel("Balance: " + balance);
amountField = new JTextField(10);
depositButton = new JButton("Deposit");
withdrawButton = new JButton("Withdraw");
balanceButton = new JButton("Balance");
JPanel panel = new JPanel();
panel.add(balanceLabel);
panel.add(new JLabel("Amount:"));
panel.add(amountField);
panel.add(depositButton);
panel.add(withdrawButton);
panel.add(balanceButton);
depositButton.addActionListener(this);
withdrawButton.addActionListener(this);
balanceButton.addActionListener(this);
add(panel);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String amountStr = amountField.getText();
double amount = 0;
try {
amount = Double.parseDouble(amountStr);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(this, "Invalid amount!");
return;
}
if (e.getSource() == depositButton) {
balance += amount;
balanceLabel.setText("Balance: " + balance);
JOptionPane.showMessageDialog(this, "Deposit successful!");
} else if (e.getSource() == withdrawButton) {
if (balance >= amount) {
balance -= amount;
balanceLabel.setText("Balance: " + balance);
JOptionPane.showMessageDialog(this, "Withdrawal successful!");
} else {
JOptionPane.showMessageDialog(this, "Insufficient funds!");
}
} else if (e.getSource() == balanceButton) {
JOptionPane.showMessageDialog(this, "Balance: " + balance);
}
}
public static void main(String[] args) {
new BankApp();
}
}
```
这个示例程序使用了Swing来构建图形用户界面。它有一个包含当前余额的标签,一个文本框用于输入存取款金额,三个按钮用于执行存款、取款和余额查询操作。
在`actionPerformed`方法中,我们首先从文本框中获取输入的金额,并将其转换为`double`类型。如果输入的不是有效的数字,我们会显示一个错误消息框并返回。接下来,根据点击的按钮,我们更新余额并显示相应的成功或失败消息框。如果余额不足,我们会显示一个“资金不足”的消息框。
最后,我们在`main`方法中创建一个`BankApp`对象,这将启动整个程序。
阅读全文