Use Java drawString to achieve the following text alignment

I want to use Java2D drawString to achieve the following features.

However, I have an idea how to achieve the next text alignment?

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

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

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

+5
source share
3 answers

To align the text, you can determine the width of the text you are viewing, and then subtract that width from the x-coordinate. eg:

g.drawString(s, rightEdge - fontMetrics.stringWidth(s), y);
+15
source

To speed this up, I designed Lawrence's 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);
+6

It does not apply drawString, but in the general case, if you want to print sets of lines formatted in a fixed width, you can simply generate each line as a line by combining the fields there with the required number of spaces between them. The code will 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 Lawrence Gonçalves pointed out, this only works for fixed-size fonts.

0
source

All Articles