简体   繁体   中英

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.

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:

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.

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:

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.

That explains why only the last rectangle seems to be drawn - all of them were drawn, in fact, but in the exact same coordinates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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