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

时间:2013-02-15 23:28:51

标签: java netbeans static applet

人们对这个错误提出了很多疑问,但是我找不到能够帮助我处理我正在处理的代码的答案。我想这与拥有一个实例或某事有关?

我希望用户能够在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();

3 个答案:

答案 0 :(得分:1)

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

或者使它成为静态方法。

答案 1 :(得分:1)

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

答案 2 :(得分: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();
    }