简体   繁体   English

从另一个包含Graphics g的类中调用方法[JAVA]

[英]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. 如您所见,我试图将其称为gameOBJ.Draw,但它给了我错误。 This is the error: The method Draw(Graphics) in the type GameObjects is not applicable for the arguments () 这是错误:GameObjects类型的Draw(Graphics)方法不适用于参数()

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

}

} }

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. 这里的关键是:您必须了解自己在做什么:当draw()方法应该在“某物上”绘制时,您必须将该东西传递给它,例如,首先创建该窗口,然后获取图形对象属于窗户。

To fix of that compilation error you can pass a graphics object. 要解决该编译错误,您可以传递graphics对象。

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.) 例如,您可以使用Windows图形(但是,这可能不是您的任务/项目的要求。对于JDK 10 Window.TITLE不存在,我怀疑它是否也存在于较早的版本中。)

Optionally: By conventions method names in Java should start with small cases characters so the method name should be draw . 可选:按照惯例,Java中的方法名称应以小写字母字符开头,因此应使用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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM