Align text with Java Graphics 2d

Can someone tell me how to cut text directly in Java 2d?

Here's the code, it draws a column of text that naturally aligns to the 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

+6
java java-2d
source share
1 answer

In your paintComponent () method, you can use FontMetrics to get the width of the line you want to draw:

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

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

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

+13
source share

All Articles