JApplet:无法在静态上下文中引用非静态方法错误

问题描述:

人们询问了这个错误很多,但我一直无法找到能够帮助我解决我正在处理的代码的答案。我想这是关于有一个实例或什么的?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(); 

它不是一个静态方法;您需要一个GridJApplet的实例才能调用实例方法。

或者让它成为一个静态方法。

您正在调用GridJApplet类的getGridSize()方法,而不是该类的实例。 getGridSize()方法未被定义为静态方法。因此,您需要在实际的GridJApplet实例上调用它。

的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(); 
    }