2013-02-15 96 views
-1

人們詢問了這個錯誤很多,但我一直無法找到能夠幫助我解決我正在處理的代碼的答案。我想這是關於有一個實例或什麼的?JApplet:無法在靜態上下文中引用非靜態方法錯誤

我希望用戶能夠在GUI(GridJApplet)中輸入數字並點擊「Go」將該數字傳遞給JPanel(GridPanel)以將網格重繪爲該寬度和高度。

我已經嘗試在GridJApplet中創建一個getter和setter,但不能在我的其他類中使用getter,它給了我錯誤「無法在靜態上下文中引用非靜態方法getGridSize()」。我正在使用NetBeans,尚未完成此代碼。我真的不明白如何讓用戶輸入在其他課程中工作。

這裏是GridJApplet代碼

public void setGridSize() { 
size = (int) Double.parseDouble(gridSize.getText()); 
    } 

public int getGridSize() { 
return this.size; 
    } 

這是GridPanel中

代碼
public void executeUserCommands(String command) { 
    if (command.equals("reset")) { 
     reset(); 
    } else if (command.equals("gridResize")) { 
       NUMBER_ROWS = GridJApplet.getGridSize(); //error occurs here 
      } 

    repaint(); 

回答

1

它不是一個靜態方法;您需要一個GridJApplet的實例才能調用實例方法。

或者讓它成爲一個靜態方法。

1

您正在調用GridJApplet類的getGridSize()方法,而不是該類的實例。 getGridSize()方法未被定義爲靜態方法。因此,您需要在實際的GridJApplet實例上調用它。

0

的Java 101:

不要這樣做:

public void executeUserCommands(String command) { 
    if (command.equals("reset")) { 
     reset(); 
    } 
    else if (command.equals("gridResize")) { 
         // WRONG 
     NUMBER_ROWS = GridJApplet.getGridSize(); //error occurs here 
    } 

相反:

else if (command.equals("gridResize")) { 
     // You must specify an *instance* of your class (not the class name itself) 
     NUMBER_ROWS = myGridJApplet.getGridSize(); 
    } 
相關問題