我希望使用Java2D drawString来实现以下外观.
但是,我有0想法如何实现以下文本对齐?
正如我们所看到的,"日期:","开放:",......都是左对齐的.
并且"09年11月30日","1262.000",......都正确对齐.
alt text http://sites.google.com/site/yanchengcheok/Home/drawstring.png
Lau*_*ves 18
要右对齐文本,您可以计算出正在渲染的文本的宽度,然后从x坐标中减去该宽度.例如:
g.drawString(s, rightEdge - fontMetrics.stringWidth(s), y);
Run Code Online (Sandbox Code Playgroud)
为了加快速度,我详细阐述了劳伦斯的回答:
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);
Run Code Online (Sandbox Code Playgroud)