-1

人们经常询问这个错误,但我无法找到对我正在处理的代码有帮助的答案。我想这与有一个实例或什么有关?

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

3 回答 3

1

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

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

于 2013-02-15T23:31:20.863 回答
1

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

于 2013-02-15T23:32:02.190 回答
0

爪哇 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();
    }
于 2013-02-15T23:34:43.883 回答