J L
J L

Reputation: 75

Calling a method from a different class containing Graphics g [JAVA]

im playing around with graphics and hit a bit of a roadblock. I can't seem to call my other class containing my graphics. Thanks in advance. As you can see i tried to call it as gameOBJ.Draw but its giving me errors. This is the error: The method Draw(Graphics) in the type GameObjects is not applicable for the arguments ()

public class Testing{

public boolean running = true;
public static void main(String[] args) {
    GameObjects gameOBJ = new GameObjects();
    gameOBJ.Draw();
    Window window = new Window(Window.WIDTH, Window.HEIGHT, Window.TITLE);
}






public class GameObjects{

public void Draw(Graphics g) {
    g.setColor(Color.BLACK);
    g.fillRect(0, 0, Window.WIDTH, Window.HEIGHT);

}

}

Upvotes: 2

Views: 715

Answers (2)

Prashant Zombade
Prashant Zombade

Reputation: 482

To fix of that compilation error you can pass a graphics object.

For example you can use windows graphics (But this may not be the requirement of your task/project. With JDK 10 Window.TITLE is not present, I doubt if it was there in earlier versions as well.)

Optionally: By conventions method names in Java should start with small cases characters so the method name should be draw.

public static void main(String[] args) {
    GameObjects gameOBJ = new GameObjects();

    //Pass the graphics object to the Draw method   
    Window window = new Window(Window.WIDTH, Window.HEIGHT, Window.TITLE);
    Graphics graphics =window.getGraphics() ; 
    gameOBJ.Draw(graphics);
}

Upvotes: 2

GhostCat
GhostCat

Reputation: 140457

Here:

gameOBJ.Draw();

There:

public void Draw(Graphics g) 

The method signature expects you to pass an argument, your invokation does not. Simply can't work that way.

The key thing here: you have to understand what you are doing: when your draw() method should draw "on something" then you have to pass that something to it, for example by first creating that window, to then fetch the graphics object belonging to the window.

Upvotes: 2

Related Questions