How can i return a value from a void method in java(如何从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方法返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从java中的void方法返回值
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01