Search code examples
javastaticdrawstring

How do I use nonstatic methods?


I have been searching for a while, and the documentation nor Google return a good answer. I just started using java, so help me out here. I am getting an error with

Graphics.drawString('hello',10, 10);

However all the documentation is telling me is that I nedd to use str,int, int. My error is:

Cannot make a static reference to the non-static method drawString(str,int,int) from the type Graphics

So does anyone know how to fix this?


Solution

  • You need to have an instance of Graphics to use, exactly as the error message says.

    i.e.,

    Graphics graphics = new Graphics();
    graphics.drawString("hello", 10, 10);
    

    Basically, static methods are invoked from the class, while non-static methods must be invoked using an actual object of that class.

    You will need to get the Graphics instance from somewhere, though, as the Graphics constructor is protected rather than public, and the class itself is abstract. (For a beginner, all this means is that you need to already have the object somewhere to work with, since you can't create it directly for yourself.)

    Also, side note: the single quote is used for char literals, while the double quote is used for String literals.