Reputation: 186
Is there any simple way to set a boundary for text on one side in Graphics2D for Java? For example, I have a rank card that displays a player's rank, and as the rank # increases in size, I want the line to expand backwards, not forwards. As you can see in the image, "Rank #24" is lined up perfectly with a line below it. If this number ever becomes 3 or 4 digits long, I want the text to get pushed backwards so the end still lines up perfectly with the line below.
Is there a simple way to do this with Graphics2D, or should I just calculate the shift myself based on how large the rank number is?
Upvotes: 0
Views: 127
Reputation: 324098
Use the FontsMetrics
class of your Graphics
object in the paintComponent()
method to get the size of the String.
Then you calculate the starting point for painting the String based on the width and your desired end point:
FontMetrice fm = graphics.getFontMetrics();
int width = fm.stringWidth("Rank #1235");
Upvotes: 2