Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align text with Java Graphics 2d

Tags:

java

java-2d

Can anyone tell me how to alight text right in Java 2d?

Here's the code, it draws a column of text that is naturally aligned left.

Font yFont = new Font("Arial", Font.BOLD, 13);

interval = 0;

g2d.setFont(yFont);
for (String l : binLabels) {
     g2d.drawString(l, 0, (135 + interval));
     interval = interval + 15;
}

Driving me crazy. Thanks y'all

slothishtype

like image 478
slotishtype Avatar asked Nov 24 '10 16:11

slotishtype


1 Answers

In your paintComponent() method you can use the FontMetrics to get the width of the string you want to paint:

FontMetrics fm = getFontMetrics( getFont() );
int width = fm.stringWidth("your string here");

Then you calculate the offset where to start painting based on the width of the component.

The question is why are you trying to do this. You can just use a JLabel and set its alignment to the right.

like image 126
camickr Avatar answered Sep 21 '22 00:09

camickr