无法从GUI变为主类

时间:2018-03-01 20:07:02

标签: java user-interface getter-setter

我正在尝试使用getter来检索用户将输入到GUI中的一些变量,但是它为我提供了“无法从静态上下文引用的非静态方法”错误。我试过让我的getter和setter静态,但是没有用。我不知道从那里去哪里。这是我的代码: 主:

public class creditInfoSystem {
    String name = infoGUI.getName();

    public static void main(String[] args) {
        new infoGUI();       
    }

    public void getData() {     
    }
}

来自GUI类的Getters + Setters:

public void setName(String newName){  
    name = newName;    
}

public String getName(){
    return name;
}

public void setCustNum(double newCustNum){  
    custNum = newCustNum;
}

public double getCustNum(){
    return custNum;
}

public void setCreditLimit(double newCreditLimit){  
    creditLimit = newCreditLimit;
}

public double getCreditLimit(){
    return creditLimit;
}

public void setPrevBalance(double newPrevBalance){  
    prevBalance = newPrevBalance;
} 

public double getPrevBalance(){
    return prevBalance;
}

public void setCurrentPurchases(double newCurrentPurchases){  
    currentPurchases = newCurrentPurchases;
}

public double getCurrentPurchases(){
    return currentPurchases;
}

public void setPayments(double newPayments){  
    payments = newPayments; 
}

public double getPayments(){
    return payments;
}

public void setCreditsReturns(double newCreditsReturns){
    creditsReturns = newCreditsReturns;
}

public double getCreditsReturns(){
    return creditsReturns;
}

public void setLateFees(double newLateFees){
    lateFees = newLateFees;
}

public double getLateFees(){
    return lateFees;
}

如果需要,我可以提供更多部分代码。

2 个答案:

答案 0 :(得分:0)

首先,重命名您的类InfoGUICreditInfoSystem,从大写开始,它是一个Java约定。

然后,当你执行InfoGUI.getName()时,你试图访问一个必须是静态的类方法。你想要做的是创建一个InfoGUI实例并访问它的实例方法。

此外,您的name变量应该是静态的,因为您在静态方法中使用它,即public static void main

public class CreditInfoSystem {

   private static String name;

   public static void main(String[] args) {
      // Create an instance of your InfoGUI class
      InfoGUI infoGuiInstance = new InfoGUI();
      // Call the getter on the instance you just created
      name = infoGuiInstance.getName();
   }

}

重命名的InfoGUI类:

class InfoGUI {

  String name;

  public void setName(String newName) {
    name = newName;
  }

  public String getName() {
    return name;
  }
}

答案 1 :(得分:0)

问题是creditInfoSystem类不知道你指的是哪个infoGUI类。尝试将infoGUI设为creditInfoSystem参数并从中检索数据。

public class creditInfoSystem {
    private InfoGUI infoGUI;

   public creditInfoSystem(InfoGUI gui){
    infoGUI = gui;
    name = infoGUI.getName();
  }

  public static void main(String[] args) {
    InfoGUI infoGUI = new infoGUI();
    CreditInfoSystem sys = new creditInfoSystem(infoGUI);

  }
}
  

如果您正在构建swing / FX GUI:

我可以预测的一个问题是知道GUI中的名称何时实际设置。您应该考虑将GUI设置为CreditInfoSystem是GUI属性的主程序。然后,当单击按钮或执行其他操作时,将从GUI输入并传递到CreditInfoSystem