3

Context

The following code produces a "nice" looking "Hello World"

graphics.drawString("Hello World", 30, 30);

Now, if instead, I draw each character string, and manually advance by fontMetrics.getCharWidth(c) then I end up with a narrow/crowded looking "Hello World".

Questions

Why does this happen? What else do I need to add to, besides each character's "advance", to ensure that the characters are well spaced?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user1383359
  • 2,673
  • 2
  • 25
  • 32
  • 1
    See also the `GlyphVector` as shown in [this answer](http://stackoverflow.com/a/6296381/418556). Note that positions of letters might be affected by whether there is a white-space character before it and if not, what the preceding character is. Why exactly are you trying to get the widths of individual characters? – Andrew Thompson May 20 '12 at 04:08

1 Answers1

2

which method in Graphics do you use to render char ? here is the code that I wrote and it runs perfectly and results of both rendering methods are exactly the same, would you please share that part of your code ?

public class Test1 extends JPanel{

public static void main(String[] args) {

    Test1 test = new Test1() ;

    JFrame frame = new JFrame() ;
    frame.add(test) ;
    frame.setSize(800 , 600) ;
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
    frame.setVisible(true) ;

}


@Override
public void paint(Graphics g) {     
    String text = "This is a text , Hello World!" ;

    g.drawString(text, 0, 100) ;        
    drawString(text, g, 0, 120) ;       
}

private void drawString (String s , Graphics g , int x , int y){
    for (int c1=0 ; c1 < s.length() ; c1++){

        char ch = s.charAt(c1); 
        g.drawString(ch+"", x, y) ;
        x+= g.getFontMetrics().charWidth(ch) ;
    }
}

}

fahim ayat
  • 312
  • 5
  • 10
  • I'm an lazy idiot for not producing a minimal-working-example. As it turns out, the problem was that I was reading the FontMetrics for the _wrong_ font -- which is why my manual calculations failed. – user1383359 May 20 '12 at 08:11