Stil203
Stil203

Reputation: 21

Adding a health bar to a character

I need a health bar to decrement according to the character's remaining HP. However I wouldn't know how to do that because the way my game loads the images

ImageIcon ii = new ImageIcon("Textures/Health/Health100.png");
healthBar = ii.getImage();

I need it to change to replace 100 in "Health100.png" with the characters current health. But I don't think I could replace the 100 with a variable so I wouldn't know how to do that.

Thanks in advance for any help.

Upvotes: 0

Views: 3585

Answers (3)

jeff
jeff

Reputation: 4333

You can preload the images which will be better than reloading images as health fluctuates.

When you load your game

 for (int i = 0; i < 100; ++i)
   healthImg[i] = new ImageIcon("Textures/Health/Health" + health + ".png");

Then in your game loop

 healthBar = healthImg[health];

But as the other Jeff suggested, it may be better for you to just not use images (unless your health bar is very fancy)

Upvotes: 3

Jeff
Jeff

Reputation: 3707

Instead of having an Image for each health increment and instead of loading all those images into memory (either one at a time or as a lookup list) you can just create a BufferedImage instance of the right dimensions (width/height) and draw directly onto its Graphics object using the Java2D APIs. You could refresh the image as the character's health changes without needing to rely on physical image files.

Upvotes: 5

cjol
cjol

Reputation: 1495

Can you not simply concatenate the health into the string? e.g.

int health = 100; // change this variable as appropriate
ImageIcon ii = new ImageIcon("Textures/Health/Health" + health + ".png");

Upvotes: 3

Related Questions