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
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); }
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.
The four primary types of text alignment include left aligned, right aligned, centered, and justified.
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With