我正在尝试使用动作侦听器来更新ATM类程序中的“Balance”值。我目前仍然坚持一旦更改完成后更新Balance的原始值的方法。许多不同的动作听众也可以改变这个值,例如。提取5英镑,存入£X等。
这是我在界面中添加按钮的地方:
protected void buildGUI(){
int balance = 10; //sets the initial balance of the user
...
JButton withdraw5 = new JButton("Withdraw \u00a35");
Withdraw5Listener w5 = new Withdraw5Listener(screen,balance);
withdraw5.addActionListener(w5);
JButton withdraw10 = new JButton("Withdraw \u00a310");
Withdraw10Listener w10 = new Withdraw10Listener(screen,balance);
withdraw10.addActionListener(w10);
JButton withdraw20 = new JButton("Withdraw \u00a320");
Withdraw20Listener w20 = new Withdraw20Listener(screen,balance);
withdraw20.addActionListener(w20);
//adds action listener to the deposit button
JButton deposit = new JButton("Deposit");
DepositListener dl = new DepositListener(screen, inputLabel,balance, withdraw5, withdraw10, withdraw20);
deposit.addActionListener(dl);
这里是我制作动作监听器类的地方(除了一些小细节之外,它们几乎相互重复,所以这里只是其中之一)。
import javax.swing.*;
import java.awt.event.*;
public class Withdraw5Listener implements ActionListener {
private int balance;
private JTextArea screen;
public Withdraw5Listener(JTextArea display, int money){
balance = money;
screen = display;
}
public void actionPerformed(ActionEvent e){
if (balance > 5){
balance = balance - 5;
screen.setText("You have withdrawn \u00a35 \n" + "Your balance is " + balance);
System.out.println("Withdrawn \u00a35");
}
}
}
当然,这些类中的每一个都只使用10的原始余额值,那么如何才能让它改变原始值呢?
谢谢大家的帮助!