如何从java中的void方法返回值

2022-01-19 00:00:00 return void java

好的,所以我有这段代码,显然渲染方法中的g = gd"没有修改g"的字段值.

Ok so i have this code and obviously the "g = gd" from the render method isnt modifying the field value of "g".

我怎样才能让渲染方法修改字段g?

How can i make it so that the render method modifies the field g?

我想要一个图形字段,这样我就可以使用图形在渲染方法之外打印字符串,但我真的不知道该怎么做.

I want to have a graphics field so i can use graphics to print strings outside the render method but i really have no idea how to do that.

private Graphics g;

private BufferedImage background;

public Tutorial(Core core){
    background = core.getResources().getImage(4);
}

public void render(Graphics gd) {
    g = gd;
    g.drawImage(background, 0, 0, null);
}

好的,这是整个课程我如何修改它以使 displayMessage 工作?在 render() 之前调用了 tick() ,这可能是一个问题?

ok this is the whole class how can i modify it so that the displayMessage will work ? tick() is called before render() , that might be a problem?

package com.andrewxd.spaceinvaders.levels;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import com.andrewxd.spaceinvaders.main.Core;

public class Tutorial implements Levels{

    private Graphics g;

    private BufferedImage background;

    public Tutorial(Core core){
        background = core.getResources().getImage(4);
    }

    public void render(Graphics gd) {
        g = gd;
        g.drawImage(background, 0, 0, null);
    }

    public void tick() {
        displayMessage("Welcome", 200,200);
    }

    public void displayMessage(String message, int x, int y) {
        g.setFont(new Font("ARIAL", Font.BOLD, 20));
        g.setColor(Color.RED);
        g.drawString(message, x, y);
    }

    public void displayMessage(String message, int x, int y, Font font) {
        g.setFont(font);
        g.setColor(Color.WHITE);
        g.drawString(message, x, y);
    }

    public void displayMessage(String message, int x, int y, Font font, Color color) {
        g.setFont(font);
        g.setColor(color);
        g.drawString(message, x, y);
    }

}

推荐答案

  • 你不能从 void 方法返回值,这就是 void 方法的目的,它会做它所做的事情并完成.

    • You can't return a value from a void method, that's the purpose of void method, it does what it does and finish.

      Java 是按值传递的,当你传递一个引用类型时,它的地址不会改变,但它的属性会受到改变的影响.

      Java is pass-by-value, when you pass a reference type, its address won't be changed but its attributes will be effected by the change.

相关文章