有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用action listener更新其他类的变量

我正在尝试使用一个动作侦听器来更新ATM类程序中的“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);

这里是我制作action listener类的地方(它们几乎是彼此的副本,保存了一些小细节,所以这里只是其中的一个)

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,那么我如何让它改变原始值呢

谢谢大家的帮助


共 (0) 个答案