Minor centered text fixes

master
John 2022-06-06 12:21:12 -04:00
parent f5e501d8ef
commit 424e71eb74
1 changed files with 8 additions and 6 deletions

View File

@ -4,22 +4,24 @@ public final class TextManager {
// utility class, constructor is private to prevent initialization // utility class, constructor is private to prevent initialization
private TextManager() {} private TextManager() {}
private static void drawTextBox(Graphics g, int y, int xOffset, int xWidth, int yHeight, int totalWidth, private static void drawCenteredTextBox(Graphics g, int y, int xWidth, int yHeight, int totalWidth,
String text, Color backgroundColor, Color textColor) { String text, Color backgroundColor, Color textColor) {
int newX = (totalWidth - xWidth)/2; int newX = (totalWidth - xWidth)/2;
int newY = y - yHeight/2; int newY = y - yHeight/2;
g.setColor(backgroundColor); g.setColor(backgroundColor);
g.drawRect(newX, newY, xWidth, yHeight); g.drawRect(newX, newY, xWidth, yHeight);
g.setColor(textColor); g.setColor(textColor);
drawCenteredString(g, y, xOffset, xWidth, text); drawCenteredString(g, y, newX, xWidth, text);
} }
private static void drawCenteredString(Graphics g, int y, int xOffset, int xWidth, String text) { private static void drawCenteredString(Graphics g, int y, int x, int xWidth, String text) {
int x; int newX, newY;
// get font size // get font size
FontMetrics metrics = g.getFontMetrics(); FontMetrics metrics = g.getFontMetrics();
// determine x for the text // determine x for the text
x = xOffset + (xWidth - metrics.stringWidth(text)) / 2; newX = x + (xWidth - metrics.stringWidth(text)) / 2;
// center y (half is above y value, half is below y value)
newY = y - (metrics.getAscent() - metrics.getDescent())/2;
// draw centered string // draw centered string
g.drawString(text, x, y); g.drawString(text, newX, newY);
} }
} }