Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Java drawString to achieve the following Text alignment

Tags:

java

I wish to use Java2D drawString to achieve the following looks.

However, I have 0 idea how I an achieve the following text alignment?

As we can see, "Date:", "Open:", ... are all being aligned to left.

And "30-Nov-09", '1262.000", ... are all being aligned to right.

alt text http://sites.google.com/site/yanchengcheok/Home/drawstring.png

like image 840
Cheok Yan Cheng Avatar asked Jan 30 '10 18:01

Cheok Yan Cheng


People also ask

What is drawString in Java?

The drawString() method, shown below, takes as parameters an instance of the String class containing the text to be drawn, and two integer values specifying the coordinates where the text should start. public void paint(Graphics g) { g. drawString("abc", 25, 25); }

How do you align text in a label in Java?

You can specify where in the label's display area the label's contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

Which of these are examples of text alignment?

The four primary types of text alignment include left aligned, right aligned, centered, and justified.


2 Answers

To right-align text you can figure out the width of the text you're rendering, and then subtract that width from the x-coordinate. eg:

g.drawString(s, rightEdge - fontMetrics.stringWidth(s), y);
like image 72
Laurence Gonsalves Avatar answered Sep 17 '22 22:09

Laurence Gonsalves


Just to speed it up I elaborated Laurence answer:

Graphics2D g2 = (Graphics2D)graphics;
g2.setFont(new Font("monospaced", Font.PLAIN, 12)); // monospace not necessary
FontMetrics fontMetrics = g2.getFontMetrics();
String s = "Whatever";
g2.drawString(s, rightEdge - fontMetrics.stringWidth(s), y);
like image 45
Vit Bernatik Avatar answered Sep 18 '22 22:09

Vit Bernatik