[英]How to pass method from class A to class B
There are 3 files: 有3个文件:
1. Annuuity.java
2. AnnuityDueGUI.java // GUI for Annuity Due
2. AnnuityDueResultGUI.java //GUI for the result
Under AnnuityDueGUI.java: 在AnnuityDueGUI.java下:
public double calculateFADGUI(){
//FVA = A{[(1+i)^n – 1] / i} (1+i)
String amountStr = amount.getText() ; //convert string to double
dAmount = Double.parseDouble(amountStr) ;
String iStr = iText.getText() ;
dInterest = Double.parseDouble(iStr) ;
String periodStr = period.getText() ;
dPeriod = Double.parseDouble(periodStr) ;
iPeriod = (int)dPeriod ;
due = new Annuity(dAmount, dInterest, iPeriod) ;
System.out.println(due.calculateFAD()) ;
return due.calculateFAD() ; //calculateFAD() is under Annuity.java
}
Under AnnuityDueResultGUI.java: 在AnnuityDueResultGUI.java下:
AnnuityDueGUI due ;
public AnnuityDueResultGUI(AnnuityDueGUI due){ //1st solution failed
this.due = due ;
}
public void grabResult(){ //1st solution failed
result = this.due.calculateFADGUI() ;
}
public AnnuityDueResultGUI(){
JPanel p6 = new JPanel() ;
p6.setLayout(new GridLayout(2, 1)) ;
p6.add(new JLabel("you will have approximately $" + result)) ;
// other codes
}
From AnnuityDueGUI.java I am able to see the result of due.calculateFAD() . 从AnnuityDueGUI.java中,我可以看到due.calculateFAD()的结果。 But, I would like to display the result under AnnuityDueResultGUI.java
但是,我想在AnnuityDueResultGUI.java下显示结果
I already did put them under a package named 'GUI' and also did import AnnuityDueGUI.java and Annuity.java. 我已经将它们放在名为“ GUI”的软件包下,并且也导入了AnnuityDueGUI.java和Annuity.java。
I did the steps that was recommended in this forum on my other same question using unregisterd user. 我使用未注册的用户对另一个相同的问题执行了此论坛中建议的步骤。 But, it did not work(the passed result is 0).
但是,它不起作用(传递的结果为0)。 That's why I'm posting the same question again with more details.
这就是为什么我要再次发布相同的问题并提供更多详细信息。
Please assist and thank you in advance. 请协助并提前感谢您。
I think you forgot to call the grabResult()
method. 我认为您忘记了调用
grabResult()
方法。
public AnnuityDueResultGUI(AnnuityDueGUI due){
this.due = due ;
grabResult(); // calling this will store the value in the "result" instance variable
JPanel p6 = new JPanel() ;
p6.setLayout(new GridLayout(2, 1)) ;
p6.add(new JLabel("you will have approximately $" + result)) ;
// other codes
}
private void grabResult(){
result = this.due.calculateFADGUI() ;
}
On a side note, you should avoid calling public methods of a non-final class in your constructor. 附带说明,您应该避免在构造函数中调用非最终类的公共方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.