[英]How to pass method from class A to class B
有3個文件:
1. Annuuity.java
2. AnnuityDueGUI.java // GUI for Annuity Due
2. AnnuityDueResultGUI.java //GUI for the result
在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
}
在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
}
從AnnuityDueGUI.java中,我可以看到due.calculateFAD()的結果。 但是,我想在AnnuityDueResultGUI.java下顯示結果
我已經將它們放在名為“ GUI”的軟件包下,並且也導入了AnnuityDueGUI.java和Annuity.java。
我使用未注冊的用戶對另一個相同的問題執行了此論壇中建議的步驟。 但是,它不起作用(傳遞的結果為0)。 這就是為什么我要再次發布相同的問題並提供更多詳細信息。
請協助並提前感謝您。
我認為您忘記了調用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() ;
}
附帶說明,您應該避免在構造函數中調用非最終類的公共方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.