我正在尝试编写2D游戏,以使用Array绘制地面纹理,但我想将名称从line0递增到line1,但我不知道如何。
BufferedImage line0[] = {/*graphics*/}
BufferedImage line1[] = {/*graphics*/}
BufferedImage line2[] = {/*graphics*/}
BufferedImage lines[] = {
line0,
line1,
line2
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int rectWidth = GameEngine.PREFERRED_GRID_SIZE_PIXELS; /* ground tile width */
int rectHeight = GameEngine.PREFERRED_GRID_SIZE_PIXELS; /* ground tile height */
for(int i = 0; i < GameEngine.NUM_ROWS; i++){ /* NUM_ROWS is the frame height */
for(int j = 0; j < lines.lenght(); j++){
/* draw the textures here (lines array) */
}
}
}
答案 0 :(得分:0)
您可以使用Java Reflections API来实现此目的,方法是获取类的字段名称,然后通过字段名称获取其值。
下面是如何使用反射的示例代码。您可以对其进行修改以用于您的课程。
Class aClass = MyObject.class
Field field = aClass.getField("someField");
MyObject objectInstance = new MyObject();
Object value = field.get(objectInstance);
field.set(objetInstance, value);
以下是与您所拥有的课程类型更相似的示例:
public class ReflectionDemo
{
public static void main(String args[]) throws Exception
{
Class<ReflectionDemoClass> clazz = ReflectionDemoClass.class;
ReflectionDemoClass objectInstance = new ReflectionDemoClass("Avinash", "Sagar", "Stack", "Overflow");
for (int i = 0; i < 4; i++)
{
Field field = clazz.getField("line"+i);
Object value = field.get(objectInstance);
System.out.println(value.toString());
}
}
}
class ReflectionDemoClass
{
public String line0;
public String line1;
public String line2;
public String line3;
public String lines[] =
{ line0, line1, line2, line3 };
public ReflectionDemoClass(String line0, String line1, String line2, String line3)
{
this.line0 = line0;
this.line1 = line1;
this.line2 = line2;
this.line3 = line3;
}
}