我真的是 Java 新手。我以为我现在已经想出了一些东西,但我有一个问题证明不是这样!
好的!这里是。我有这段代码(已编辑 - 非原创):
import java.util.*;
import java.awt.*;
public class MyClass extends HisClass
{
public void drawRectangle(int width, int height)
{
int x1 = this.getXPos();
int y1 = this.getYPos();
java.awt.Graphics.drawRect(x1, y1, width, height);
}
public static void main(String[] args)
{
AnotherClass theOther = new AnotherClass();
MyClass mine = new MyClass(theOther);
mine.move();
}
}
它给我的错误是这样的:
MyClass.java:66: error: non-static method drawRect(int,int,int,int) cannot be referenced from a static context
你能给我一个解决方案吗? 我们将不胜感激。谢谢。
最佳答案
java.awt.Graphics.drawRect(x1, y1, width, height);
drawRect
方法不是静态的。您应该以某种方式获取 Graphics 类的实例以使用它:-
(graphicsInstance).drawRect(x1, y1, width, height);
由于 Graphics
类是抽象
,所以您需要找到合适的方法来实例化您的 Graphics 对象,以获取 graphicsInstance
您可以使用 GraphicsContext
绘制任何您想要的东西。GraphicsContext 是属于 Graphics
类的对象,您可以使用它来 drawRect()
查看这些帖子。可能有用:-
关于Java: "non-static method drawRect"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771885/