【问题标题】:How to call a help method如何调用帮助方法
【发布时间】:2012-10-28 11:14:39
【问题描述】:

我有一个家庭作业,要求我们为一个小图形程序编写一个辅助方法。我遇到的问题是它一直说我有错误。

找不到符号 - 方法 drawPolygon(gp, int, int)。

我错过了什么?

PS。我知道 GraphicsPanel 代码不在这里,但更想知道为什么我会收到“找不到符号”错误。当我写 just drawPolygon(gp, 50, 4) 时,它会编译没有任何错误,但它也不会在面板中绘制任何东西。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class G5 {
    public static void drawPolygon(GraphicsPanel gp, int sideCount, int sideLength) {
        for (int i = 0; i < 4; i++) {
            gp.draw(sideLength);
            gp.turn(360 / sideCount);
        }
    }

    public static void main(String[] args) {
        GraphicsPanel gp = new GraphicsPanel();
        gp.setBackgroundColor(Color.BLACK);
        gp.delay(1000);
        int x = gp.getWidth() / 2;
        int y = gp.getHeight() / 2;
        gp.setLocation(x, y);

        gp.setColor(Color.RED);
        gp.drawPolygon(gp, 50, 4);

        gp.clear();
    }
}

【问题讨论】:

标签: java graphics panel


【解决方案1】:

该方法是 G5 类的静态方法。它不是 GraphicsPanel 的实例方法。所以你必须调用它使用

G5.drawPolygon(gp, 50, 4);

而不是

gp.drawPolygon(gp, 50, 4);

为了能够像您正在做的那样调用它,该方法必须在 GraphicsPanel 类(或其任何超类)中定义,不带 static 关键字。

阅读this section of the Java tutorial,了解实例方法和静态方法的区别。

【讨论】:

  • 哦!!!我明白了,呃!! >.
  • 静态在这里无关紧要。请注意,您可以在实例上调用静态方法,它只会忽略该实例。
  • 当然很重要。如果该方法不是静态的,则 OP 必须实例化一个新的 G5 才能调用辅助方法。并且调用静态方法作为实例方法是一种非常非常糟糕的做法。
【解决方案2】:
 gp.drawPolygon(gp, 50, 4);

您正在GraphicsPanel 实例中寻找方法,而不是在您的类中。因为它是一个静态方法,所以使用

G5.drawPolygon(gp, 50, 4);

改为

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2015-06-18
    相关资源
    最近更新 更多