gpt4 book ai didi

java - 如何有效地引用其他类的对象

转载 作者:行者123 更新时间:2023-11-30 09:24:28 25 4
gpt4 key购买 nike

我有主类、GUI 类和 CheckingAccount 类。我应该制作一个带有 radioButtons 的 Jframe 来处理 CheckingAccount 对象,并且不应该在 main 中有逻辑!所以我想我可以在 main 中创建一个 CheckingAccount 对象并获得对它的某种引用,可能是通过方法或构造函数参数,然后在 GUI 类中使用它(与 Action 监听器一起使用,以及类似的东西。)问题是,例如在 GUI 类中,在 actionPerformed 方法中我不能像user.setBlahBlah...//user在main中是一个CheckingAccount对象。你能帮我解决这个问题吗?

最佳答案

为您的 GUI 类提供一个 CheckingAccount 变量,该变量在 setCheckingAccount(CheckingAccount checkingAccount) 方法中或通过构造函数参数提供引用。然后您可以在 GUI 中引用该对象(或者更好的是,如果您有 Control 类)。

public class MyGui {
private CheckingAccount checkingAccount;
private JButton myButton = new new JButton("My Button");

public MyGui() {
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt) {
if (checkingAccount == null) {
return;
}
checkingAccount.someMethod();
}
});
}

public void setCheckingAccount(CheckingAccount checkingAccount) {
this.checkingAccount = checkingAccount;
}

}

包含类的主要方法:

public Main {
public static void main(String[] args) {
CheckingAccount checkingAccount = new CheckingAccount();
MyGui myGui = new MyGui();
myGui.setCheckingAccount(checkingAccount);
myGui.displaySomehow();
}
}

关于java - 如何有效地引用其他类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com