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.
drawRectmethod is not static.. You should get an instance of your Graphics class somehow to use it: –Since
Graphicsclass isabstract, so you need to find appropriate way to instantiate your Graphics object, to getgraphicsInstanceYou can use
GraphicsContextto draw whatever you want to.. GraphicsContext is an object belonging toGraphicsclass which you can use todrawRect()See these post. Might be useful: –
How do I initialize a Graphics object in Java?
what is a graphics context (In Java)?