简体   繁体   中英

How to center text output by drawString in Java

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.

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);

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);

有一个特定的功能可以做到这一点,我相信它叫做drawCenterString

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