Reputation: 458
I am trying to center the text output from drawString on the X coordinate in a program. I am trying to get the width of my window and devide by two to get the center but to no avail. Here is my code:
package net.minecraft.src;
import java.awt.Color;
import java.awt.FontMetrics;
import org.lwjgl.input.Keyboard;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import net.minecraft.client.Minecraft;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class GuiIngame extends Gui
{
//lots of other code here
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
String xCords = nf.format(mc.thePlayer.posX);
String yCords = nf.format(mc.thePlayer.posY);
String zCords = nf.format(mc.thePlayer.posZ);
drawString(fontrenderer, (new StringBuilder()).append("X: ").append(xCords).toString(), 20, 2, 0xe0e0e0);
drawString(fontrenderer, (new StringBuilder()).append("Y: ").append(xCords).toString(), 40, 2, 0xe0e0e0);
drawString(fontrenderer, (new StringBuilder()).append("Z: ").append(xCords).toString(), 60, 2, 0xe0e0e0);
}
It only needs to be centered on the x axis.
Upvotes: 0
Views: 4917
Reputation: 167
There is a specific function for doing this, i beleive it is called drawCenterString
Upvotes: 2
Reputation: 8702
This should do what you want:
String coord_text = new StringBuilder()).append("X: ").append(xCords).toString();
gui.drawString(fontrenderer, coord_text, gui.width/2 - fontrenderer.getStringWidth(coord_text)/2, 2, 0xe0e0e0);
Upvotes: 2
Reputation: 458
There was a integer that I didn't know of that did the job. My final code to display each line is:
drawCenteredString(fontrenderer, (new StringBuilder()).append("X: ").append(xCords).toString(), mc.displayWidth / 4, 2, 0xe0e0e0);
Upvotes: 2