开发者

Use Java drawString to achieve the following Text alignment

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/dr开发者_运维知识库awstring.png


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);


Not specific to drawString, but in general if you want to print sets of strings formatted into a fixed width you can simply generate the each line as a string by concatenating the fields there with the required number of spaces in between. The code would look something like this:

String[] makeLines(String[] labels, String[] data, int width){
   String[] lines=new String[labels.length];
   StringBuilder spaces=new StringBuilder();
   for(int i=0;i<width;i++)
      spaces.append(" ");

   for (int i=0;i<labels.length;i++){
      lines[i]=labels[i]+spaces.substring(0,width-data[i].length()-labels[i].length())+data[i];
   }
   return lines;
}

Edit: As Laurence Gonsalves pointed out, this works for fixed size fonts only.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜