简体   繁体   English

从同一个类中绘制多个字符串

[英]Drawing multiple strings from the same class

I hope this makes sense. 我希望这是有道理的。 I'm using Java with the Slick2d library, that probably doesn't matter though. 我正在将Java与Slick2d库一起使用,但这可能没关系。

My problem is, I'm trying to render multiple rectangles and strings from the same sub class, but when I do, only the last one actually renders. 我的问题是,我试图从同一个子类渲染多个矩形和字符串,但是当我这样做时,实际上只有最后一个渲染。

Here the code in my Entity class: 这是我的Entity类中的代码:

public class Entity {

    public static String name;
    public static int health, x, y;

    public Entity(String n, int h, int posx, int posy) {
        name = n;
        health = h;
        x = posx;
        y = posy;
    }

    public static void render(Graphics g) {
        g.drawString(name, x-20, y-16);
        g.drawRect(x, y, 16, 16);
    }

}

And here is how I'm trying to call it from my main class: 这就是我试图从主班级调用它的方式:

public void render(GameContainer gc, Graphics g) throws SlickException {
        new Entity("Monster1", 100, 400, 200);
        new Entity("Monster2", 100, 500, 200);
        Entity.render(g);
}

What am I doing wrong? 我究竟做错了什么? Please keep in mind I'm still new to java, so it will most likely be a really obvious problem. 请记住,我还是Java的新手,所以它很可能是一个非常明显的问题。

problem is that you should not use the static variable modifier. 问题是您不应该使用静态变量修饰符。 Remove it in all three places within the entity class and then use your new entity class as follows. 在实体类的所有三个位置将其删除,然后按如下所示使用新的实体类。

Entity m1 = new Entity("Monster1", 100, 400, 200);
m1.render(g);

Start by removing the static modifier from your variables: 首先从变量中删除static修饰符:

public String name;
public int health, x, y;

In Java, when you declare an attribute to be static , all of the instances of the class will share the exact same attribute, and if one instance changes its value, all the others will be changed, to - since it's the same attribute for all. 在Java中,当您声明一个属性为static ,该类的所有实例将共享完全相同的属性,并且如果一个实例更改其值,则所有其他实例都将更改为-因为所有实例的属性都相同。

That explains why only the last rectangle seems to be drawn - all of them were drawn, in fact, but in the exact same coordinates. 这就解释了为什么似乎只绘制了最后一个矩形-实际上所有这些矩形都是在完全相同的坐标下绘制的。

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

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