如何从java中的void方法返回值 [英] How can i return a value from a void method in java

查看:75
本文介绍了如何从java中的void方法返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有这段代码,显然渲染方法中的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.

      这篇关于如何从java中的void方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆