lwjgl, SLick-util - fixating string midpoint to a coordinate.

I have ammo counter and it varies in length depending on how much ammo is left. Im using

RenderThread.graphics2D.drawString(20, 55, weapon.getAmmo() + "/" + weapon.getMaxAmmo());

to draw the ammo counter. Problem is the x and y coordinates are the upper left coordinates. but i would like to get the midpoint coordinates. So that no matter how much ammo is used the “/” is still at the same exact coordinates. How can it be done?

Simple way is to mandate that getAmmo() always returns a value within some range, i.e. 0-999 so that it will always have a bounded number of digits and render it separately from the “/”:


RenderThread.graphics2D.drawString(20, 55, weapon.getAmmo());
RenderThread.graphics2D.drawString(20, 85, "/" + weapon.getMaxAmmo()); //arbitrary 85, you will have to manually determine based on font size, etc.

Another, slightly more complicated but better looking method is to pad the weapon.getAmmo() string with leading spaces to ensure it’s a fixed length (only works for monospaced fonts):


String ammo = "";
int numLeadingSpaces = maxAmmoDigits - Integer.toString(weapon.getAmmo()).length();
for(int i = 0; i < numLeadingSpaces; i++)
      ammo += " ";
ammo += weapon.getAmmo();

RenderThread.graphics2D.drawString(20, 55, ammo + "/" + weapon.getMaxAmmo());

Other than that, slick might have a method for determining the length of a string of a certain font, but I’m not familiar enough to know of it.