Java: "non-static method drawRect"错误

标签 java drawrect

我真的是 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()

查看这些帖子。可能有用:-

How do I initialize a Graphics object in Java?

what is a graphics context (In Java)?

关于Java: "non-static method drawRect"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12771885/

相关文章:

ios - 在 drawRect :(CGRect) 中做动画的方法

ios - 如何刷新自定义绘制单元格的颜色?

iphone - 在drawInRect:rect崩溃,我有解决方案,但不知道如何?

java - ClassCastException 在 Arrays.sort(...) 中使用转换后的列表

java - 我应该在 Java 中用什么替换小结构?

java - 如何比较包含字符串的对象?

ios - 触发drawRect重绘 View 的按钮

java - 相当于 php exit() 或 die() 的 Tomcat Servlet 代码

java - 无法使用java的Runtime.getRuntime().exec()隐藏文件夹

ios - 裁剪时drawRect是 "wasteful"吗?有其他选择吗?