Search code examples
javadrawrect

Java: "non-static method drawRect" error


I am really new in Java. Thought I had figure some stuff out by now, but I have a problem that proves otherwise!

Ok! Here it is. I have this code (Edited - Not original):

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();
    }
}

The error it gives me is this:

MyClass.java:66: error: non-static method drawRect(int,int,int,int) cannot be referenced from a static context

Can you please provide me with a solution? It would be very appreciated. Thanks.


Solution

  • java.awt.Graphics.drawRect(x1, y1, width, height);
    

    drawRect method is not static.. You should get an instance of your Graphics class somehow to use it: -

    (graphicsInstance).drawRect(x1, y1, width, height);
    

    Since Graphics class is abstract, so you need to find appropriate way to instantiate your Graphics object, to get graphicsInstance

    You can use GraphicsContext to draw whatever you want to.. GraphicsContext is an object belonging to Graphics class which you can use to drawRect()

    See these post. Might be useful: -

    How do I initialize a Graphics object in Java?

    what is a graphics context (In Java)?